<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8"><style><?php global $rep,$vues,$css; include $rep.$css['bootstrap']; ?></style>
        <title></title>
        <script src="css/jquery-3.5.1.js"></script>
        <link rel="stylesheet" href="css/VuePrincipale.css">
        
    </head>
    <?php 
      $tp_str = implode(",", array_keys($dVueQuestions));
      require_once('BDD/SqliteDb.php');
        $db = new SqliteDb();
        $dateVerif = array();

        $user = $_SERVER['REMOTE_USER'];
      //die($tp_str);               
    ?>
    
    <body id="vuep">
        <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">Base De Données</a>
             <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
               <span class="navbar-toggler-icon"></span>
             </button>
             <div class="collapse navbar-collapse" id="navbarResponsive">
               <ul class="navbar-nav ml-auto">
                   <?php            foreach ($dVueQuestions as $tp => $question){ 
                                        $numTp  = str_replace('tp', '', $tp);
                                        $q="SELECT * FROM dateTp WHERE numTp=?";
                                        $prp=$db->prepare($q);      
                                        $prp->bindParam(1,  $numTp);
                                        $result = $prp->execute();
                                        $row = $result->fetchArray();
                                        $date = date('Ymd');
                                        if($date < $row['dateDebut'] || $date>$row['dateFin']) {
                                            $dateVerif[$tp] = 0;
                                            if($_SESSION['typeSession'] != 'LJLf1') continue;
                                        } else $dateVerif[$tp] = 1;
                                                ?>
                 <li class="nav-item">
                     <a style = "text-transform:uppercase;" class="nav-link js-scroll-trigger" id="<?php echo $tp; ?>" onclick="changerSection('<?php echo $tp;?>','<?php echo $tp_str ;?>')" ><?php echo $tp; ?></a>
                 </li>                
                   <?php }?>
               </ul>
             </div>
           </div>
         </nav>
        <header class="bg-primary text-white">
           <div class="container text-center">
                <h1>TP</h1>
                <p class="lead"></p>
            </div>
        </header>
<div id='allp'>
    <div style="font-weight: bold" id="Temps-Restant" hidden></div>
        <form method="get" 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 une question" />           
        </form>
        <?php         foreach ($dVueQuestions as $tp => $questions){ //die(print_r($questions)); 
                            if($dateVerif[$tp] == 0){
                                if($_SESSION['typeSession'] == 'LJLf1')
                                    $indispo = '(<i>Indisponible pour les non admin</i>)';
                                else continue;
                            }  ?>
        
        <section id="<?php echo 'o'.$tp; ?>">            
          <div class="container">
            <div class="row">
              <div class="col-lg-8 mx-auto">
                  <?php $numTp  = str_replace('tp', '', $tp);
                        $q="SELECT * FROM dateTp WHERE numTp=?";
                        $prp=$db->prepare($q);      
                        $prp->bindParam(1,  $numTp);
                        $result = $prp->execute();
                        $row = $result->fetchArray();
                        
                        $jdeb = substr($row['dateDebut'], 6, 2);
                        $mdeb = substr($row['dateDebut'], 4, 2);
                        $adeb = substr($row['dateDebut'], 0, 4);
                        $dateDebut = $jdeb.'-'.$mdeb.'-'.$adeb;
                        
                        $jfin = substr($row['dateFin'], 6, 2);
                        $mfin = substr($row['dateFin'], 4, 2);
                        $afin = substr($row['dateFin'], 0, 4);
                        $dateFin = $jfin.'-'.$mfin.'-'.$afin;
                  
                  ?>
                <h2 style = "text-transform:uppercase;  "  ><?php echo $tp; ?></h2><?php echo 'Disponible du '.$dateDebut.' jusqu\'au '.$dateFin.' à 00h00m01s. ';//afficher dates ?>
                <form  class="adm" style ="margin-left: 150px; ">
                    <input type="button"  value="Modifier les dates" onclick="ModifierDates(<?php echo str_replace('tp', '', $tp);?>)" />
                </form>
                
                <form  id="questionsForm<?php echo $tp ?>" method="get" name="Exam">
                        <?php $i=0; //shuffle($dVueQuestions); 
                        foreach ($questions as $q) {
                            /*if($nbQ > $_SESSION['nbQuestions']) 
                                break; */ ?>
                        <p><?php  $i++;  echo $q->getNumQuestion() .'.'.$q->getQuestion().'.'.str_repeat("&nbsp;", 8).'<i>barème : '.$q->getBareme().' point(s)</i>';  $_SESSION['num']=array();  $_SESSION['num'][$i] =$q->getNumQuestion();  ?> <br/>
                          <?php 
                                $query = $db->prepare('SELECT * FROM TpSauvegarde WHERE numTp=? AND numQuestion=? AND idEtudiant=?');   
                                $numTp =$q->getNumTp();
                                $numQuestion = $q->getNumQuestion();
                                $query->bindParam(1,$numTp);
                                $query->bindParam(2,$numQuestion);
                                $query->bindParam(3,$user);
                                $result = $query->execute();
                                $reponseSave = $result->fetchArray();                          
                            
                            ?>
                            <textarea name="question<?php echo $q->getNumQuestion(); ?>" id="question<?php echo $q->getNumQuestion().$q->getNumTp(); ?>"  rows="5" cols="70"
                              ><?php  echo $reponseSave['reponse']; ?></textarea>
                            <p><input class="submitQuestionData" type="button" value="Valider" onclick="SubmitQuestionData(<?php echo $q->getNumQuestion(); ?>,<?php echo $q->getNumTp(); ?>);" >
                              <input class="executerQuestion" type="button" value="Exécuter" onclick="ExecuterQuestion(<?php echo $q->getNumQuestion(); ?>,<?php echo $q->getNumTp(); ?>);" >
                                <span id="inp-centre" ><input  class="modifierQuestion adm" type="button" value="Modifier" onclick="ModifierQuestion(<?php echo $q->getNumQuestion(); ?>,<?php echo $q->getNumTp(); ?>)" >
                            <input class="supprimerQuestion adm"  type="button" value="Supprimer" onclick="SupprimerQuestion(<?php echo $q->getNumQuestion(); ?>,<?php echo $q->getNumTp(); ?>);" ></span>
                            <span id="inp-gauche" ><input  class="monterQuestion adm" type="button" value="Monter" onclick="MonterQuestion(<?php echo $q->getNumQuestion(); ?>,<?php echo $q->getNumTp(); ?>)" >
                            <input  class="descendreQuestion adm" type="button" value="Descendre" onclick="DescendreQuestion(<?php echo sizeof($questions); ?>,<?php echo $q->getNumQuestion(); ?>,<?php echo $q->getNumTp(); ?>)" ></span></p>
                        </p>
                        <div id="resultatsQuestions<?php echo $q->getNumQuestion().$q->getNumTp(); ?>">
                            <!-- les résultats s'affichent içi -->
                        </div><br/>
                        <?php $i++; } //fin foreach ?>
                </form>
              </div>
            </div>
          </div>
        </section><?php } ?>
               

        <!--<a href="vues/VueAdmin.php" class="a-ajout"><button id="btn-ajout">Ajouter Une Question</button></a>-->
        <!--<a href="vues/VueLibre.php" class="a-ajout"><button>Creation table</button></a>-->
        
        
        
        <form method="get" role="form">
            <input id="inp-questions" class="bouton" type="submit" name="action" value="Afficher les questions" hidden>
            <input id="inp-ret" type="submit" name="action" value="Retour au menu principal" >
            <input id="btn-ajout" type="submit" name="action"  value="Ajouter une question" />
        </form>
        
        <form id="frm-export" class="adm">
                <input type="button" value="Exporter" onclick="ExporterTp()" />
        </form>
        <form id="frm-exportnoteqcm" class="adm">
            <input type="button" value="Exporter Les Notes" onclick="ExporterNotesTp()" />
        </form>

        <?php
        
        ?>
        <div id="resultats">
            <!-- les résultats s'affichent içi -->
        </div><br/>
        <input type="text" id="verif-ad" value="<?php echo $_SESSION['typeSession'];?>" hidden/>

</div>      
       <script type="text/javascript">
          function ExporterNotesTp(){
              $.get("Traitement/Sauvegarde/ExportNotes.php", {},
                  function(data) {
                    alert(data+"Les notes sont exportées vers  /var/www/html/BD2A/Notes/tp/");
                       $('#resultatsQuestions22').html(data);
              });    
          }                     
            var tempsMin =60 ;
            var total_secondes =60*tempsMin;
            tempsMin = parseInt(total_secondes/60);
            secondes = parseInt(total_secondes%60);
            document.getElementById("Temps-Restant").innerHTML='Temps restant: ' + tempsMin + ' minutes ' + secondes + ' secondes';
            function init(){
                document.getElementById("Temps-Restant").innerHTML='Temps restant: ' + tempsMin + ' minutes ' + secondes + ' secondes';
                setTimeout("TempsRestant()",999);
            }
            function TempsRestant(){
                document.getElementById("Temps-Restant").innerHTML='Temps restant: ' + tempsMin + ' minutes ' + secondes + ' secondes' ;
                if(total_secondes <=0){
                    setTimeout('document.Exam.submit()',1);
                } 
                else {
                    total_secondes = total_secondes -1;
                    tempsMin = parseInt(total_secondes/60);
                    secondes = parseInt(total_secondes%60);
                    setTimeout("TempsRestant()",999);
                }
            }
            init();
       
            function ExporterTp(){
                    type = 'tp';
                    $.get("Traitement/Export.php", { type:type}, function(data) {
                        alert(data+"Les notes sont exportées vers  /var/www/html/BD2A/imports/tp/tp_exportes.txt ");
                    });
            }
                
            function ModifierDates(tp){                
                $.get("Traitement/VueGestionTp.php", { tp:tp},
                function(data) {
                     $('#vuep').empty();
                     $('#vuep').html(data);
                  });
            }
            $(document).ready(function() {
              var section = localStorage.getItem("sectionTp");
              if( section !== null){
                  changerSection(section, $('#tp_keys').val());
                  
              }
              else{
                var tps = $('#tp_keys').val();
                 if(!tps) exit();
                var i = 0;
                var numTp;
                tpk = tps.split(",");
                tpk.forEach(function(entry) {
                    numTp = entry;
                    while(!$("#o"+numTp).length){
                        numTp++;
                    }
                    if(i==0) $("#o"+numTp).show();
                    else $("#o"+numTp).hide();
                    i++;
                    console.log(numTp);
                });
              }
          });

            
            function changerSection(tp,keys){
                if(!keys) exit();
                var qcm = tp;
                var numTp;
                tpk = keys.split(",");
                tpk.forEach(function(entry) {
                    numTp = entry;
                    while(!$("#o"+numTp).length){
                        numTp++;
                    }
                    $("#o"+numTp).hide();                   
                    console.log(numTp);
                });               
                localStorage.setItem("sectionTp", tp);
                $("#o"+tp).show();
   
            }
            function ExecuterQuestion(numQuestion,numTp) {
                    //document.write($('#demo'+numQuestion).val());
                    var tx = $('#question'+numQuestion+numTp).val() ; 
                    var txt =  tx.replace(/^\s+/g, "");

                    txt = txt.trim();

                    if(!(txt.toUpperCase().includes('CREATE') && txt.toUpperCase().includes('FUNCTION'))) {
                        if (txt.charAt(txt.length - 1) == ';') {
                          txt = txt.substr(0, txt.length - 1);
                        }
                    } 
                    $.get("Traitement/AffichageDemo.php", { textbox: txt},
                    function(data) {
                         $('#resultatsQuestions'+numQuestion+numTp).html(data);
                         //$('#demoForm')[0].reset();
                      });
            } 

            function SubmitQuestionData(numQuestion, numTp) {
                //document.write($('#demo'+numQuestion).val());
                
                var tx = $('#question'+numQuestion+numTp).val() ; 
                var txt =  tx.replace(/^\s+/g, "");

                txt = txt.trim();

                if(!(txt.toUpperCase().includes('CREATE') && txt.toUpperCase().includes('FUNCTION'))) {
                    if (txt.charAt(txt.length - 1) == ';') {
                      txt = txt.substr(0, txt.length - 1);
                    }
                }


                $.get("Traitement/Correcteur.php", { textbox : txt, numQuestion : numQuestion, numTp : numTp},
                function(data) {
                     $('#resultatsQuestions'+numQuestion+numTp).html(data);
                     //$('#questionsForm')[0].reset();
                  });
                
                $.get("Traitement/Sauvegarde/TpSave.php", { textbox : txt, numQuestion : numQuestion, numTp : numTp},
                function(data) {
                     //$('#resultatsQuestions'+numQuestion+numTp).html(data);
                     //$('#questionsForm')[0].reset();
                  });
                  
            } 
            
             function SupprimerQuestion(numQuestion,numTp) {
                var result = confirm("Êtes-vous sûr de vouloir supprimer la question "+numQuestion+" du TP "+numTp+" ?");
                if(!result) return;
                $.get("Traitement/Suppression.php", {  numQuestion : numQuestion, numTp : numTp},
                function(data) {
                     //$('#resultatsQuestions'+numQuestion).html(data);
                     //$('#questionsForm')[0].reset();
                        $('#inp-questions').trigger("click");
                  });
                  
            } 
            
            function ModifierQuestion(numQuestion, numTp) {
                
                $.get("Traitement/Modification.php", {  numQuestion : numQuestion, numTp : numTp },
                function(data) {
                    $('#vuep').empty();
                     $('#vuep').html(data);
                     //$('#questionsForm')[0].reset();
                     //location.reload();
                  });

            } 
          
            function MonterQuestion(numQuestion, numTp) {
                
                if(numQuestion > 1){
                    $.get("Traitement/Ordre.php", {  numQuestion : numQuestion, numTp : numTp },
                    function(data) {

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

                         //$('#questionsForm')[0].reset();
                        $('#inp-questions').trigger("click");
                         //window.location.replace("index.php");
                      });
                }
            }
            
            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);
             
             
            $( document ).ready(function() {
                var ad = $('#verif-ad').val();
                             
                if(ad == 'LJLf1')
                    $( ".adm").show();
                else $( ".adm").remove();
                
            });
        </script>
        <!-- Footer -->
        <footer class="py-5 bg-dark">
          <div class="container">
            <p class="m-0 text-center text-white">IUT Clermont-Ferrand 2020</p>
          </div>
          <!-- /.container -->
        </footer>

        <!-- Bootstrap core JavaScript -->
        <script src="vendor/jquery/jquery.min.js"></script>
        <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

        <!-- Plugin JavaScript -->
        <script src="vendor/jquery-easing/jquery.easing.min.js"></script>

        <!-- Custom JavaScript for this theme -->
        <script src="js/scrolling-nav.js"></script>
         
    </body>
</html>
