<?php 
    //SACAR EN PRODUCCION
    //error_reporting(E_ALL);
    //ini_set('display_errors', 'On');
    //FIN SACAR

    $curso = 'G3D';
    $mysqli = new mysqli('10.0.0.125', 'syseva', '5UM415i6u3', 'sys_utest');
    $mysqli->set_charset("utf8");
    if (!$mysqli) {
      echo 'No pudo conectarse a mysql';
      exit;
    }

    $cursos = array();

    $res = $mysqli->query("SELECT * FROM dispaula360_cursos");
    $tipos = $mysqli->query("SELECT * FROM dispaula360_tipos")->fetch_all(MYSQLI_ASSOC);
    while($f = $res->fetch_object()){
      $curso = array();
      $curso["nombre"] = $f->titulo;
      $curso["id"] = $f->id;
      $curso["unidades"] = array();
      $res_unidades = $mysqli->query("SELECT * FROM dispaula360_unidad WHERE id_curso = ".$curso["id"]);
      while($g = $res_unidades->fetch_object()){
        $unidad = array();
        $unidad['titulo'] = $g->titulo;
        $unidad['id'] = $g -> id;
        $unidad['num'] = $g -> numero;
        $unidad['temas'] = array();
        $res_temas = $mysqli->query("SELECT * FROM dispaula360_tema WHERE id_unidad = ".$unidad["id"]);
        while($h = $res_temas->fetch_object()){
          $tema = array();
          $tema['titulo'] = $h->titulo;
          $tema['id'] = $h -> id;
          $tema['num'] = $h -> numero;
          $tema['contenidos'] = array();
          $res_contenidos = $mysqli->query("SELECT * FROM dispaula360_contenidos WHERE id_tema = ".$tema["id"]);
          while($i = $res_contenidos->fetch_object()){
            $contenido = array();
            $contenido['titulo'] = $i->titulo;
            $contenido['id'] = $i -> id;
            $contenido['num'] = $i -> numero;
            $contenido['componentes'] = array();
            $res_componentes = $mysqli->query("SELECT * FROM dispaula360_componentes WHERE id_contenido = ".$contenido["id"]);
            while($j = $res_componentes->fetch_object()){
              $componente = array();
              $componente['filt_tipo'] = current(array_filter($tipos, function($k) use ($j) {return $k['id'] == $j->tipo;}, ARRAY_FILTER_USE_BOTH ))['tipo'];
              $componente['titulo'] = $j->titulo; 
              $componente['descripcion'] = $j->descripcion; 
              $componente['embed_url'] = $j->embed_url; 
              $componente['download_url'] = $j->download_url;
              $componente['display_url'] = $j->display_url;  
              $contenido['componentes'][] = $componente;
            }
            $tema['contenidos'][] = $contenido;
          }
          $unidad['temas'][] = $tema;
        }
        $curso["unidades"][] = $unidad;
      }
      $cursos[] = $curso;
    }
  ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aula 360</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
    <link href="./assets/css/style.css" rel="stylesheet">
    <link href="./assets/css/emineduc2.css" rel="stylesheet">
    <style>
        
        li.comp-container {
          background: #e7e7e7;
          border-radius: 20px;
          margin: 0 auto;
          width: 99%;
          list-style: none;
        }
    
        li.comp-container iframe{
          /* max-width:80%; */
          margin:0 auto;
          display:block;
        }
        .holds-the-iframe {
          background:url(../images/loader.gif?2) center center no-repeat;
        }

        .holds-the-iframe {
          position: relative;
          padding-bottom: 56.25%;
          height: 0;
          overflow: hidden;
          width: 877.67px;
          height: 600px;
        }
        .holds-the-iframe iframe {
            position: absolute;
            top:0;
            left: 0;
            width: 100%;
            height: 100%;
        }

        main{
            margin-bottom:50px;
        }

        .iframe-container {
          
          max-width: 1200px;
          min-width: 700px;
          height: 500px;
          }

          .iframe-video-wrapper {
            
          width: 100%;
          height: 100%;
          overflow: hidden;
          }

          .iframe-video {
          height: 100%;
          width: 100%;
          }
          .image-course-title{
            margin-top: 10px;
            text-align:center;
          }

          .aula360-header img{
            width:100%;
          }

          .aula360-cursos img{
            max-width:70%;
          }
          
    
      </style>
      <script type="text/javascript">
        function addHTMLcodehover(html_code,modal_id,contenido_numero,contenido_titulo){
          $('.modal.fade').attr("id",modal_id);
          var modal_title_html = "<strong>Contenido "+contenido_numero+":</strong> "+contenido_titulo; 
          $('.modal-title').html(modal_title_html);
          // $('.modal-body ul').html(html_code);
          // $('#'+modal_id).modal();
          // $('#modal_id').click();
          $()
            }     
        function addHTMLcodeclick(html_code,modal_id,contenido_numero,contenido_titulo){
          // $('.modal.fade').attr("id",modal_id);
          // var modal_title_html = "<strong>Contenido "+contenido_numero+":</strong> "+contenido_titulo; 
          // $('.modal-title').html(modal_title_html);
          $('.modal-body ul').html(html_code);
          $('#'+modal_id).modal();
          // $('#modal_id').click();
          $()
            }                     
            
          
    </script>

</head>
<body>
    <header>
      <div class="container-lg px-0">
        <div class="aula360-header row text-center m-0 p-0">
          <div class="col-lg-2"></div>  
          <div class="col-lg-8 col-12 px-0">
            <img src="./assets/img/banner.png" class="p-0" alt="">
          </div>  
          <div class="col-lg-2"></div>  
        </div>
      </div>
    </header>
    <main class="aula360-main">
        <div class="container-lg px-4">
            <div class="row aula360-titulo mt-4 mb-4">
                <div class="col-lg-2"></div>
                <div class="col-lg-8 col-12 aula360-titulo-texto pt-2 pb-2">
                    Sobre el proyecto
                </div>
                <div class="col-lg-2"></div>
            </div>
            <div class="row aula360-parrafo aula360-about">
                <div class="col-lg-2"></div>
                <div class="col-lg-8 col-12">
                    <p>
                        Aula 360 es una iniciativa liderada por el Ministerio de Educación que nace para apoyar la implementación del nuevo currículo escolar de Formación Diferenciada Humanista-Científica. El Laboratorio de Educación del Centro de Modelamiento Matemático desarrolló tres Rutas Digitales de Aprendizaje, que son secuencias de actividades interactivas diseñadas para apoyar procesos de enseñanza aprendizaje, enfocadas en el desarrollo de habilidades.
                    </p>
                    <p>
                        La Rutas entregan a las y los docentes acceso a una gran variedad de recursos flexibles, apoyando la enseñanza de la matemática en las asignaturas de “Geometría 3D”, “Límites, Derivadas e Integrales” y “Probabilidades y Estadística Descriptiva e Inferencial”.
                    </p>
                    <p> 
                        En esta página se encuentran recursos interactivos y multimedia para facilitar los procesos de enseñanza y aprendizaje de estas asignaturas, los que a su vez están organizados según las unidades del currículo, temas y contenidos
                    </p>
                </div>
                <div class="col-lg-2"></div>
            </div>
            <div class="row aula360-titulo aula360-curso mt-4 mb-4">
                <div class="col-lg-2"></div>
                <div class="col-lg-8 col-12 aula360-titulo-texto">
                    Cursos
                </div>
                <div class="col-lg-2"></div>
            </div>
            <div class="row aula360-parrafo aula360-cursos">
                <div class="col-lg-2"></div>
                <div class="col-lg-8">
                    <div class="container">
                        <div class="row">
                            <div class="col-lg-4 col-12 text-center">
                                <img src="./assets/img/c1.png" alt="">
                                <p class="image-course-title"> GEOMETRÍA 3D </p>
                              </div>
                              <div class="col-lg-4 col-12 text-center">
                                <img src="./assets/img/c3.png" alt="">
                                <p class="image-course-title"> PROBABILIDADES Y ESTADÍSTICA </p>
                            </div>
                              <div class="col-lg-4 col-12 text-center">
                                <img src="./assets/img/c2.png" alt="">
                                <p class="image-course-title"> LÍMITES, DERIVADAS E INTEGRALES </p>
                              </div>
                        </div>
                        <!-- <div class="row text-center">
                            <div class="col-4">
                                GEOMETRÍA 3D
                            </div>
                            <div class="col-4">
                                LÍMITES, DERIVADAS E INTEGRALES
                            </div>
                            <div class="col-4">
                                PROBABILIDADES Y ESTADÍSTICA
                            </div>
                        </div> -->
                    </div>
                </div>
                <div class="col-lg-2"></div>
            </div>
            
            <button id="despliega-todo" onclick="displayAll();"><span  style="display: none" id="button-text-desplegar">Desplegar todo</span><span id="button-text-replegar">Replegar todo</span></button>
            <?php 
              foreach($cursos as $curso){ 
            ?>
            <script>
              function displayAll(){
                $('.aula360-titulo-unidad-texto').click();
                $('.aula360-titulo-tema-texto').click();
                $('#button-text-desplegar').toggle();
                $('#button-text-replegar').toggle();
              }
            </script>
            <!-- Inicio Curso -->
            <div class="row aula360-titulo aula360-curso mt-4 mb-4">
                <div class="col-lg-2"></div>
                <div class="col-lg-8 col-12 aula360-titulo-texto">
                    <?php echo $curso['nombre']; ?>
                </div>
                <div class="col-lg-2"></div>
            </div>

            <!-- Inicio Unidad -->
            <?php 
              foreach($curso["unidades"] as $unidad){ 
                $cod_unidad = preg_replace('/\s+/', '', $curso['nombre']).$unidad['num'];
                ?>
            <div class="row aula360-titulo-unidad mt-4 mb-3">
                <div class="col-lg-2"></div>
                <div class="col-lg-8 col-12 aula360-titulo-unidad-texto text-white pb-2 pt-2" data-bs-toggle="collapse" href="#unidad<?php echo $cod_unidad;?>">
                    <strong>UNIDAD <?php echo $unidad['num']?>:</strong> <?php echo str_replace('ñññ','?:',$unidad['titulo']);?>
                </div>
                <div class="col-lg-2"></div>
            </div>
            
            <!-- Inicio Temas -->
            <div class="collapse" id="unidad<?php echo $cod_unidad;?>">
            <?php
              foreach($unidad["temas"] as $tema){ 
                $cod_tema = preg_replace('/\s+/', '', $unidad['titulo']).$tema['num'];
                $cod_tema = str_replace(",", "", $cod_tema);
            ?>
            <div class="row aula360-titulo-tema mt-4 mb-3">
                <div class="col-lg-2"></div>
                <div class="col-lg-8 col-12 pb-2 pt-2 aula360-titulo-tema-texto" data-bs-toggle="collapse" href="#temas<?php echo $cod_tema;?>">
                    <div class="circle me-2"></div><strong>Tema <?php echo $tema['num']?>:</strong> <?php echo str_replace('ñññ','?:',$tema['titulo']);?>
                </div>
                <div class="col-lg-2"></div>
            </div>
            <!-- Inicio Contenidos -->
            <div class="collapse" id="temas<?php echo $cod_tema;?>">
                <?php
                  foreach($tema["contenidos"] as $contenido){ 
                    $cod_contenido = preg_replace('/\s+/', '', $contenido['titulo']).$contenido['num'];
                    $cod_contenido = str_replace(",", "", $cod_contenido);
                ?>
                <div class="row aula360-taller mt-1 mb-2">
                    <div class="col-lg-2"></div>
                    <div class="col-lg-8 col-12">
                        <div class="container">
                            <div class="row">
                              <?php
                              // lista de combinaciones codificadas:
                              // ñññ = ?:
                              $html_var = "";
                                foreach($contenido['componentes'] as $componente){

                                $html_var .= "<li class='comp-container mb-3 mt-3 px-3 px-lg-5 py-4'>
                                                <div>
                                                <h3>".str_replace('"','“',str_replace("ñññ","?:",$componente['titulo']))."</h3>
                                                <p>".str_replace('"','“',$componente['descripcion'])."</p>";
                                    

                                    if ($componente['filt_tipo'] == 'video'){
                                      

                                      $url_final_e = strpos(is_null($componente['embed_url'])?'':$componente['embed_url'], 'http')!== false ? $componente['embed_url'] : '..'.$componente['embed_url'];
                                      
                                      $html_var.= "<video style='display:block;margin:0 auto;width:90% ' controls><source src='".$url_final_e."' type='video/mp4'>Tu navegador no soporta la reproducción de videos HTML5.</video><br/>";
                                      $url_final = strpos(is_null($componente['download_url'])?'':$componente['download_url'], 'http')!== false ? $componente['download_url'] : '..'.$componente['download_url'];
                                      $html_var.="<a class='btn btn-primary mt-3 mb-3' target='_blank' href='".$url_final."' target='_blank'>Descargar</a>";
                                    }
                                    elseif ($componente['filt_tipo'] == 'geogebra') {
                                      $iframe_html = str_replace('"',"'",is_null($componente['embed_url'])?'':$componente['embed_url']);

                                      // $onload_str =  "javascript:(function(o){o.style.height=`\${o.contentWindow.document.body.scrollHeight}px`;}(this));";
                                      $onload_str =  "";
                                      // $style_str = "height:200px;width:100%;border:none;overflow:hidden;";
                                      $style_str = "width:100%;border:none;overflow:hidden;";
                                      $iframe_html = strstr($iframe_html, 'scrolling=', true)." onload='".$onload_str."' style='".$style_str."' ".strstr($iframe_html, 'scrolling=');                                      
                                      $html_var.= "<div class='holds-the-iframe'>".$iframe_html."</div>";
                                      $html_var.="
                                      <br/>
                                      <a class='btn btn-primary mt-3 mb-3' target='_blank' href='".$componente['display_url']."' target='_blank'>Ver en Geogebra</a>
                                      ";
                                      // <a class='btn btn-primary mt-3 mb-3 mr-3' target='_blank' href='".$componente['download_url']."' target='_blank'>Descargar</a>
                                    }
                                    elseif ($componente['filt_tipo'] == 'gif') {
                                      $html_var.="
                                      <img class='mt-3 mb-3' src='../".$componente['download_url']."' />
                                      <br/>
                                      <a class='btn btn-primary mt-3 mb-3' target='_blank' href='../".$componente['download_url']."' target='_blank'>Descargar</a>
                                      ";

                                    }
                                    elseif ($componente['filt_tipo'] == 'html') {
                                      $url_final_e = strpos(is_null($componente['embed_url'])?'':$componente['embed_url'], 'http')!== false ? $componente['embed_url'] : '..'.$componente['embed_url'];
                                      $url_final_e = str_replace('"',"'",$url_final_e);
                                      $html_var.="<div class='iframe-container'><div class='iframe-video-wrapper'><iframe class='iframe-video' src='".$url_final_e."'></iframe></div></div>";

                                    }
                                    elseif ($componente['filt_tipo'] == 'base_de_datos') {
                                      $url_final_d = strpos(is_null($componente['download_url'])?'':$componente['download_url'], 'http')!== false ? $componente['download_url'] : '..'.$componente['download_url'];
                                      $url_final_d = str_replace('"',"'",$url_final_d);
                                      $html_var.="<a class='btn btn-primary mt-3 mb-3' target='_blank' href='".$url_final_d."' target='_blank'>Descargar</a>";

                                    }
                                    else {

                                      $url_final_e = strpos(is_null($componente['embed_url'])?'':$componente['embed_url'], 'http')!== false ? $componente['embed_url'] : '..'.$componente['embed_url'];
                                      
                                      $html_var.="<embed src='".$url_final_e."#navpanes=0&statusbar=0&toolbar=0&view=fitH' style='display:block;margin:0 auto;width:80%;height:600px;' type='application/pdf' /><br/>
                                      <a class='btn btn-primary mt-3 mb-3' target='_blank' href='".$componente['download_url']."' target='_blank'>Descargar</a>";
                                      
                                    }

                                $html_var.="</div></li><br/>";

                                }
                              ?>
                                
                                <div class="col-12 aula360-taller-texto ms-3 pt-2 pb-2" data-bs-toggle="modal" data-bs-target="#modal<?php echo str_replace(',','__',$cod_contenido);?>" onmouseover="addHTMLcodehover(<?php echo "`".$html_var."`";?>,<?php echo "`modal".str_replace(',','__',$cod_contenido)."`";?>,<?php echo "`".$contenido['num']."`";?>,<?php echo "`".$contenido['titulo']."`";?>)" onclick="addHTMLcodeclick(<?php echo "`".$html_var."`";?>,<?php echo "`modal".str_replace(',','__',$cod_contenido)."`";?>,<?php echo "`".$contenido['num']."`";?>,<?php echo "`".$contenido['titulo']."`";?>)">
                                    <strong>Contenido <?php echo $contenido['num']?>:</strong> <?php echo str_replace('ñññ','?:',$contenido['titulo'])?>
                                </div>
                                
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-2"></div>
                    </a>
                </div>

                <?php
                  }
                  ?>
            </div>
            <!-- Fin Contenidos-->
                
                <?php
                  }
                ?>
                </div>
                <!-- Fin Temas -->
                <!-- Fin Unidad -->
                <?php
                  }
                ?>
            <!--Fin Curso-->
            <?php
              }
            ?>
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal_id" style="display:none">
              Launch demo modal
            </button>
            <!-- Modal contenido 1-->
              <div class="modal fade" id="modal_id" data-bs-keyboard="true" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                  <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
                  <div class="modal-content">
                      <div class="modal-header">
                      <h5 class="modal-title" id="staticBackdropLabel"><strong>Contenido 1:</strong> Titulo </h5>
                      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                      </div>
                      <div class="modal-body p-0 p-lg-3">
                        

                        <ul class="px-0 px-lg-5">
                        </ul>
                      </div>
                      <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                      </div>
                  </div>
                  </div>
              </div>
              <!--fin modal-->
        </div>
    </main>
    <!-- Footer -->
    <footer class="aula360-footer text-white container-fluid">
        <div class="container">
            <div class="row aula360-footer-logos">
                <div class="col-md-2 col-1"></div>
                <div class="col-md-2 col-12 text-md-start text-center pb-md-0 pb-5">
                    <img src="./assets/img/logofcfm.png" width="130" alt="logo fcfm">
                </div>
                <div class="col-md-4 col-12 text-center pb-md-0 pb-5">
                    <img src="./assets/img/logocmm.png" width="170" alt="logo cmm">
                </div>
                <div class="col-md-2 col-12 text-md-end text-center">
                    <img src="./assets/img/logogob.png" width="120" alt="logo gob">
                </div>
                <div class="col-2"></div>
            </div>
        </div>
    </footer>
    <!-- Footer -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>  
    <script src="https://static.sumaysigue.uchile.cl/cmmeduformacion/produccion/encuestas/inicial/js/iframeResizer.min.js?1"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="load-mathjax.js?1" id="MathJax-script" async></script>
    <script>
  
      $(function() {
        $("iframe").each(function() { 
          // $(this).attr('src', $(this).attr('src')); 
          iFrameResize({log:false,autoResize:true}, $(this)[0]);
          elsrc = $(this).attr("src");
          let elrandom = (Math.random() + 1).toString(36).substring(7);
          $(this).attr("src",elsrc+elrandom);
        });
      });

      $(document).ready(function() {     
            
            $(".modal.fade").on("hide.bs.modal", function(e) {
              $(".modal.fade .modal-body ul").html(""); // Remove the video source.
            });
          });
    </script>
</body>
</html>