<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
                <script src="css/jquery-3.5.1.min.js"></script>

        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/VuePrincipale.css">
    </head>
    <?php 
        require_once('BDD/SqliteDb.php');
        $db = new SqliteDb();
     
     //session_start();
      $tp_str = implode(",", array_keys($tabQCM));
           $user = $_SERVER['REMOTE_USER'];

    ?>
    <body id="vueqcm">       
         <input type="text" id='tp_keys' value="<?php echo $tp_str; ?>" hidden>
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark" id="mainNav">
           <div class="container">
             <a class="navbar-brand js-scroll-trigger" href="#page-top">Méthodologie </a>
            <div class="collapse navbar-collapse" id="navbarResponsive">
                   <ul class="navbar-nav ml-auto">
<?php           foreach ($tabQCM as $qcm){ if(sizeof($qcm->getQuestions())==0) continue;  ?>
                     <li class="nav-item">
                         <a style = "text-transform:uppercase;" class="nav-link js-scroll-trigger" id="<?php echo $qcm->getNum(); ?>" onclick="changerSection('<?php echo $qcm->getNum();?>','<?php echo $tp_str ;?>')" ><?php echo $qcm->getNom(); ?></a>
                     </li>                
        <?php   }?>
                   </ul>
            </div>
           </div>
         </nav>
        <header class="bg-primary text-white">
            <div class="container text-center">
                <h1>QCM</h1>
                <p class="lead"></p>
            </div>
        </header>
        <form method="get" role="form" class="adm">
          <input id="inp-ret1" type="submit" name="action" value="Retour au menu principal" >
            <input id="btn-ajout1" type="submit" name="action"  value="Ajouter QCM" />
        </form>
<?php 
    foreach ($tabQCM as $qcm){ /*if(sizeof($qcm->getQuestions())==0) continue;*/ ?>
        <section id="<?php echo 'qcm'.$qcm->getNum(); ?>">
          <div class="container">
            <div class="row">
              <div class="col-lg-8 mx-auto">
                  
                <h2><?php echo $qcm->getNum().'-'.$qcm->getNom(); ?></h2>
                <h5><?php echo $qcm->getIntroduction(); ?></h5>
                <form  class="QCMForm" method="get"  >
                        <?php 
                        foreach ($qcm->getQuestions() as $question) {
                              ?>                        
                            <p><?php  echo $question->getNumQuestion() .'.'.$question->getQuestion(); ?> <br/>
                            <?php 
                            foreach ($question->getReponse() as $r ) { 
                                if($qcm->getType() == "vraifaux") {
                                    $query = $db->prepare('SELECT count(*) FROM QcmSauvegarde WHERE numQcm=? AND numQuestion=? AND numReponse = ? AND idEtudiant=?');   
                                    $numQcm =$qcm->getNum();
                                    $numQuestion = $question->getNumQuestion();
                                    $numReponse = $r->getNumReponse();
                                    $query->bindParam(1,$numQcm);
                                    $query->bindParam(2,$numQuestion);
                                    $query->bindParam(3,$numReponse);
                                    $query->bindParam(4,$user);
                                    $result = $query->execute();
                                    $reponseSave = $result->fetchArray(); ?>                           
                                    <input type="checkbox" id="textbox<?php echo $qcm->getNum()."-".$question->getNumQuestion()."-".$r->getNumReponse(); ?>" name="radiobox<?php echo $qcm->getNum().$question->getNumQuestion();?>" value="<?php echo $r->getReponse();?>" style="margin-bottom:15px" <?php if($reponseSave['count(*)']!=0) echo 'checked'; ?>> <?php echo $r->getNumReponse().'.   '.$r->getReponse(); ?> <br/>
                    <?php       }
                                else{
                                    $query = $db->prepare('SELECT count(*) FROM QcmSauvegarde WHERE numQcm=? AND numQuestion=? AND numReponse = ? AND idEtudiant=?');   
                                    $numQcm =$qcm->getNum();
                                    $numQuestion = $question->getNumQuestion();
                                    $numReponse = $r->getNumReponse();
                                    $query->bindParam(1,$numQcm);
                                    $query->bindParam(2,$numQuestion);
                                    $query->bindParam(3,$numReponse);
                                    $query->bindParam(4,$user);
                                    $result = $query->execute();
                                    $reponseSave = $result->fetchArray();
                                    
                                     echo $r->getNumReponse().'.';?>
                                    <input type="radio" id="textbox<?php echo $qcm->getNum()."-".$question->getNumQuestion()."-".$r->getNumReponse(); ?>" name="radiobox<?php echo $qcm->getNum().$question->getNumQuestion();?>" value="<?php echo $r->getNumReponse();?>" style="margin-bottom:15px" required <?php if($reponseSave['count(*)']!=0) echo 'checked'; ?>> <?php echo $r->getReponse(); ?> <br/>
                    <?php       }
                            }
                            if($qcm->getType() == "vraifaux"){
                            ?>
                                <p> 
                                    <input class="SubmitQCMData" type="button" value="Valider" onclick="SubmitQCMData(<?php echo $qcm->getNum(); ?>,<?php echo $question->getNumQuestion(); ?>,<?php echo $question->getBareme(); ?>)" >
                      <?php }// fin if vraifaux ?>                            
                                    <span id="inp-centre">
                                        <input class="modifierQCM adm" type="button" value="Modifier" onclick="ModifierQCM(<?php echo $qcm->getNum(); ?>,<?php echo $question->getNumQuestion(); ?>);" >
                                        <input class="supprimerQCM adm" type="button" value="Supprimer" onclick="SupprimerQCM(<?php echo $qcm->getNum(); ?>,<?php echo $question->getNumQuestion(); ?>);" >
                                    </span>
                                    <span id="inp-gauche">
                                        <input class="monterQCM adm" type="button" value="Monter" onclick="MonterQCM(<?php echo $qcm->getNum(); ?>,<?php echo $question->getNumQuestion(); ?>)" >
                                        <input class="descendreQCM adm" type="button" value="Descendre" onclick="DescendreQCM(<?php echo $qcm->getNum(); ?>,<?php echo sizeof($qcm->getQuestions()); ?>,<?php echo $question->getNumQuestion(); ?>)" >
                                    </span>                        
                                </p>                        
                                <div id="results<?php echo $qcm->getNum().$question->getNumQuestion(); ?>">
                                    <!-- les résultats s'affichent içi -->
                                </div><br/>
                      <?php 
                        }//fin foreach 
                        if($qcm->getType() !== "vraifaux"){?>
                            <input type="button" value="Valider"  onclick="SubmitQCMDataTest(<?php echo $qcm->getNum(); ?>,<?php echo sizeof($qcm->getQuestions()); ?>)" />                
                            <div id="results<?php echo $qcm->getNum(); ?>">
                                    <!-- les résultats s'affichent içi -->
                            </div><br/>
                <?php   } 
                  ?>
                </form>
              </div>
            </div>
          </div>
        </section>
<?php } //fin foreach ?> 
                <input type="text" id="verif-ad" value="<?php echo $_SESSION['typeSession'];?>" hidden/>

        <form method="get" class="adm">
           <input id="inp-ret1" type="submit" name="action" value="Retour au menu principal" >
            <input id="btn-ajout" type="submit" name="action"  value="Ajouter QCM" />
        </form>
        <form method="get" role="form">
            <input id="inp-questions" class="bouton" type="submit" name="action" value="QCM" hidden>
        </form>

        <form id="frm-exportqcm" class="adm">
            <input type="button" value="Exporter les QCM" onclick="ExporterQcm()" />
        </form>
        <form id="frm-exportnoteqcm" class="adm">
            <input type="button" value="Exporter les notes" onclick="ExporterNotes()" />
        </form> 
        <script>
        	function ExporterNotes(){

                $.get("Traitement/Sauvegarde/ExportNotes.php", {},
                    function(data) {
                        alert(data+"Les notes sont exportées vers  /var/www/html/Methodologie/Notes/QCM/");
                         $('#results11').html(data);
                });    
            }
            function ExporterQcm(){
                    type = 'qcm';
                    $.get("Traitement/Export.php", { type:type}, function(data) {
                        alert(data+"Les qcm sont exportées vers  /var/www/html/Methodologie/imports/qcm/qcm_exportes.txt");
                    });
            }
            
            $(document).ready(function() {
              var section = localStorage.getItem("section");
                if( section !== null){
                    changerSection(section, $('#tp_keys').val());
                    
                }
                else{
                  var tps = $('#tp_keys').val();
                   if(!tps) exit();
                  var i = 0;
                  var numQcm;
                  tpk = tps.split(",");
                  tpk.forEach(function(entry) {
                      numQcm = parseInt(entry)+1;
                      while(!$("#qcm"+numQcm).length){
                          numQcm++;
                      }
                      if(i==0) $("#qcm"+numQcm).show();
                      else $("#qcm"+numQcm).hide();
                      i++;
                      console.log(numQcm);
                  });
                } 
                /////////////// FIN SECTION // DEBUT SAUVEGARDE ////
                $('input[type="checkbox"]').change(function () {
                    var name = $(this).attr('id');
                    var check = $(this).prop('checked');
                    //alert("Change: " + name + " to " + check);
                    $.get("Traitement/Sauvegarde/QcmSave.php", {id : name, check : check , type:"vraifaux"},
                    function(data) {
                         $('#results11').html(data);
                    });                               
                });    
                
                $('input[type="radio"]').change(function () {
                    var name = $(this).attr('id');
                    var check = $(this).prop('checked');
                    //alert("Change: " + name + " to " + check);
                    $.get("Traitement/Sauvegarde/QcmSave.php", {id : name, check : check, type:"test"},
                    function(data) {
                         $('#results11').html(data);
                    });        
                }); 
            });
                
            function changerSection(tp,keys){
                if(!keys) exit();
                var qcm = tp;
                var numQcm;
                tpk = keys.split(",");
                tpk.forEach(function(entry) {
                    numQcm = parseInt(entry)+1;
                    while(!$("#qcm"+numQcm).length){
                        numQcm++;
                    }
                    $("#qcm"+numQcm).hide();                   
                    console.log(numQcm);
                });               
                localStorage.setItem("section", tp);
                $("#qcm"+qcm).show();

            }
                
            function SubmitQCMData(numQcm,numQuestion,bareme) {
                var rep = [];
                var verif =  0;
                //alert($('input[name*="radiobox'+numQuestion+'"]').length);
                for(var i=1 ; i<=$('input[name*="radiobox'+numQcm+numQuestion+'"]').length ; i++){
                    if ($('#textbox'+numQcm+'-'+numQuestion+'-'+i).is(':checked')){
                        rep.push(i);
                        verif++;
                    }
                }
                if(verif == 0) return ;
                $.get("Traitement/CorrectionQCM.php", {numQcm:numQcm,  numQuestion: numQuestion, rep : rep , bareme : bareme},
                function(data) {
                     $('#results'+numQcm+numQuestion).html(data);
                  });
            } 
            
            function SubmitQCMDataTest(numQcm, nbQuestions) {
                var type = 'test';
                var rep = [];
                 
                $('#results'+numQcm).empty(); 
                for(var numQuestion=1 ; numQuestion<=nbQuestions ; numQuestion++){
                    rep[numQuestion] = [];
                    if(!$("input[name='radiobox"+numQcm+numQuestion+"']:checked").val()){
                        $('#results'+numQcm).append("<b>Veuillez répondre à toutes les questions</b>");
                        return;
                    }
                    rep[numQuestion].push($("input[name='radiobox"+numQcm+numQuestion+"']:checked").val());
                }
               
                $.get("Traitement/CorrectionQCM.php", {type : type , numQcm:numQcm,  rep : rep},
                function(data) {
                     $('#results'+numQcm).html(data);
                  });
            } 
            
            function MonterQCM(numQcm,numQuestion) {
                    if(numQuestion > 1){
                        $.get("Traitement/OrdreQCM.php", { numQcm:numQcm, numQuestion : numQuestion },
                        function(data) {

                             //$('#questionsForm')[0].reset();
                             //$('#erreur').html(data);
                             $("#inp-questions").trigger("click");
                             //window.location.replace("index.php");
                          });
                    }
                }
                
            function DescendreQCM(numQcm,nbQuestions,numQuestion) {
           //alert(nbQuestions);
               var des = 1;
                if(numQuestion < nbQuestions){
                   $.get("Traitement/OrdreQCM.php", { numQcm:numQcm,des : des , numQuestion : numQuestion },
                   function(data) {

                        //$('#questionsForm')[0].reset();
                       $("#inp-questions").trigger("click");
                        //window.location.replace("index.php");
                     });
               }
            }
                
            function SupprimerQCM(numQcm,numQuestion) 
            {
                var result = confirm("Êtes-vous sûr de vouloir supprimer la question "+numQuestion+" du qcm "+numQcm+" ?");
                if(result){
                    var type = "qcm";
                    $.get("Traitement/Suppression.php", {  numQcm :numQcm, numQuestion : numQuestion ,qcm : type},
                    function(data) {
                         //$('#results'+numDemo+numChapitre).html(data);
                         //$('#questionsForm')[0].reset();
                           $("#inp-questions").trigger("click");
                      });
                  }
            } 
            function ModifierQCM(numQcm , numQuestion) {
                $.get("Traitement/ModificationQCM.php", {  numQcm : numQcm, numQuestion : numQuestion },
                function(data) {
                    $('#vueqcm').empty();
                     $('#vueqcm').html(data);
                     //$('#questionsForm')[0].reset();
                     //location.reload();
                  });

            }
             $( document ).ready(function() {
                var ad = $('#verif-ad').val();
                             
                if(ad == 'LJLf1')
                    $( ".adm").show();
                else $( ".adm").remove();
                
        
                
                if(ad == 'test'){
                      $('#vuep').empty();
                  }
    
            });
            
             window.addEventListener('scroll',function() {       
                 localStorage.setItem('scrollPosition',window.scrollY);
             },false); 
             window.addEventListener('load',function() {
                 if(localStorage.getItem('scrollPosition') !== null)
                 window.scrollTo(0, localStorage.getItem('scrollPosition'));
             },false);
        </script>

    </body>
</html>
