<?php

global $btn_unlock_request, $lbl_unlock_comment, $ph_unlock_comment, $btn_unlock_sent ;

require("/opt/imtlazarus/config/cfg.php");
require("/opt/imtlazarus/privatephp/web_backend/webfilter.php");
require_once("/var/www/lazarus/funciones.php");
require_once("/var/www/g_common/funciones_g_common.php");


$isDev = false;
$nombre_dns = $generalconfig["nombre_dns"];
$servers = [
  "dev1.imtlazarus.com",
  "dev2.imtlazarus.com",
  "dev3.imtlazarus.com",
  "dev4.imtlazarus.com",
  "dev5.imtlazarus.com",
  "desarrollov3.imtlazarus.com",
];

if (in_array($nombre_dns, $servers)) {
  $isDev = true;
}

// NUEVO BLOQUE
if (isset($_GET['user'])){
  $_SERVER['HTTP_USER']=$_GET['user'];
}

$device_origin="extension";
require("/opt/imtlazarus/config/engine_devices.php");


$url_absoluta = "https://$generalconfig[nombre_dns]/";
$random=rand(111111, 999999);
$ahora = time();

// ENTRADA DE DATOS
$userip=$_SERVER['REMOTE_ADDR'];
$preurl=htmlspecialchars($_GET['url']);
$printable_url=htmlspecialchars($_GET['url']);
$blocked_cat=$_GET['category'];


// ANALISIS DE &url
$url_data=webfilter_analizar_url($preurl);


// envío: false o true
$envio_activo = false;

$ahora=time();

$idioma=substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);

$resultidioma=$pdo->prepare("SELECT * FROM idiomas WHERE idioma=:idioma;");
$resultidioma->bindParam(':idioma', $idioma, PDO::PARAM_STR);
$resultidioma->execute();
$cantidiomas = $resultidioma->rowCount();
if ($cantidiomas == 0){
  $idioma = "en";
  $resultidioma=$pdo->prepare("SELECT * FROM idiomas WHERE idioma=:idioma;");
  $resultidioma->bindParam(':idioma', $idioma, PDO::PARAM_STR);
  $resultidioma->execute();
}
$lang_data = $resultidioma->fetch(PDO::FETCH_ASSOC);
$idiomanombre=$lang_data[$idioma];
require ("/var/www/lazarus/$lang_data[fichero]");

header("Expires: Tue, 01 Jul 2001 06:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Strict-Transport-Security: max-age=60000; includeSubDomains");



//CONTROLAR SI ES POR TRANSMISION EN IOS
$margen=$ahora-30;

if (($dev_info['tipo']=="ios") and ($dev_status['screen_send']==1) and (intval($dev_status['screenshot_trans']) < $margen)){
  $bloqueoscreenshots=1;
} else {
  $bloqueoscreenshots=0;


  //TIPO POLITICA
  if ($dev_web_pol['duracion']>=$ahora){
    $politica=$dev_web_pol['politica_temp'];
    $supervisor_idbin=$dev_web_pol['supervisor_temp_idbin'];
    $supervisor_uuid=$dev_web_pol['supervisor_temp_uuid'];
    $permanente=0;
    $controltimer=$dev_web_pol['duracion'] - $ahora;
  } else {
    $politica=$dev_web_pol['politica_fija'];
    $supervisor_idbin=$dev_web_pol['supervisor_fijo_idbin'];
    $supervisor_uuid=$dev_web_pol['supervisor_fijo_uuid'];
    $permanente=1;
  }

  $precolor=$politica;

  //SI ES POLITICA 1 SE MIRA CONFIG
  if ($politica==1){
    if ($dev_config['incenter']==1){
      $politica=$dev_config['filtro_web'];
    } else {
      $politica=$dev_config['filtro_web_hogar'];
    }
  }


  //CONTROL DE SUPERVISOR CAUSANTE
  $consulta="SELECT administrators.*, roles.tipo, roles.show_in_block 
             FROM rel_sup_ent
             INNER JOIN administrators ON administrators.idbin=rel_sup_ent.supervisor_idbin
             INNER JOIN rel_sup_rol ON (administrators.idbin=rel_sup_rol.supervisor_idbin and rel_sup_rol.project_idbin=:project_idbin)
             INNER JOIN roles ON (roles.id=rel_sup_rol.rol and roles.project_idbin=rel_sup_rol.project_idbin)
             WHERE rel_sup_ent.project_idbin=:project_idbin and rel_sup_ent.supervisor_idbin=:supervisor_idbin;";
  $resultsql=$pdo->prepare($consulta);
  $resultsql->bindParam(':supervisor_idbin', $supervisor_idbin, PDO::PARAM_LOB);
  $resultsql->bindParam(':project_idbin', $generalconfig['project_idbin'], PDO::PARAM_LOB);
  $resultsql->execute();
  $cantsuper = $resultsql->rowCount();
  if ($cantsuper==1){
    $superdata = $resultsql->fetch(PDO::FETCH_ASSOC);
    $tiposup=$superdata['tipo'];
    if ($superdata['show_in_block']==1){
      $nombresup="$superdata[nombre] $superdata[apellidos]";
    } elseif ($superdata['show_in_block']==2){
      $nombresup="$superdata[nombre]";
    } else {
      $nombresup="";
    }
  } else {
    $nombresup="";
    $tiposup="";
  }

  //CALCULAR EL QUIEN
  if (($cantsuper==1) and ($politica!=1)){
    if ($tiposup==2){
      if ($nombresup!=""){
        $msg2 = "${msg_block_home}: <font style=\"color: black;font-size: 20px;\">${nombresup}</font>";
      } else {
        $msg2 = $msg_block_home;
      }
    } else {
      if ($nombresup!=""){
        $msg2 = "${msg_block_center}: <font style=\"color: black;font-size: 20px;\">${nombresup}</font>";
      } else {
        $msg2 = $msg_block_center;
      }
    }
  } else {
    $msg2 = $msg_block_general;
  }

  //CONTROL DE MENSAJES
  $motivo="desconocido";
  if ($cantdev!=0){
    if ($politica==2){
      //bloqueo total (rojo)
      $motivo="total";
    } elseif ($politica==9){
      //bloqueo total (negro)
      $motivo="total";
    } else {
      //bloqueo filtro (verde) y (naranja)

      $mifiltro=obtener_configuracion_filtro_web($politica);

      //CONTROL DEL BLOQUEO

      //ESTADO PREVIO POR BLOCK ALL
      if ($mifiltro['block_all']==1){
        //bloqueo total (naranja) y (verde)
        $motivo="total";
      } else {

        // TEST CATEGORIA
        $coincidencias=array_values(array_intersect($url_data['lista_cat_id'],$mifiltro['categorias']));
        if (count($coincidencias)>0){
          $motivo="categoria";
          $lista_cat_name_by_id=$url_data['lista_cat_name_by_id'];
          $categorias_arr=array();
          foreach ($coincidencias as $micat){
            $categorias_arr[]=$url_data['lista_cat_name_by_id'][$micat];
          }
        }
        if ((count($url_data['lista_cat_id'])==0) and ($mifiltro['block_unclass']==1)){
          $motivo="categoria";
          $categorias_arr=array("Unclassified");
        }

        // TEST DOMINIO BL
        if (in_array($testdom,$mifiltro['dominios_bl'])){
          $motivo="blacklist";
        }

      }

    }
  }


  // POR MOTIVO
  if ($motivo=="desconocido"){
    $msg = $msg_block_default;
  }
  if ($motivo=="total"){
    $msg = $msg_block_total;
  }
  if ($motivo=="categoria"){
    if (count($categorias_arr)>0){
      $listacat="<u>".implode("</u>, <u>",$categorias_arr)."</u>";
      $msg = "${msg_block_bycat} ${listacat}</u>";
    } else {
      $msg = $msg_block_bycat;
    }
  }
  if ($motivo=="blacklist"){
    $msg = $msg_block_blacklist;
  }

  $fichero_logo = "/var/www/lazarus/img/client/1_logo.png";
  $md5_logo = md5_file($fichero_logo);
  $logo_personalizado = $md5_logo != "3971997ac13ef1df8ea392c0e69bc71d"; //logo de imtlazarus por defecto
}

print_html_start();
print_header($msg_block_noaccess.": ".$printable_url, $url_absoluta,null,"//$generalconfig[nombre_dns]/lazarus/favicon.png");

?>
  <!-- Google Fonts -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <!-- Lato & Roboto Font -->
  <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;0,700;0,900;1,100;1,300;1,400;1,700;1,900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">

  <!-- My custom css -->
  <link href="<?= $url_absoluta ?>/css/access_denied.css?id=<?php $random ?>" rel="stylesheet">

<?php
print_head_body();
?>


  <div id="top_bar" class="header-nav sticky-top navgar-light bg-white">
    <div id="logos">
      <?php if ($logo_personalizado) { ?>
        <!-- mostrar 1 ó 2 logos -->
        <img src="/lazarus/img/client/1_logo.png?id="<?= $random ?> />
        <img src="/lazarus/img/logo_imt_color.svg?id="<?= $random ?> />
      <?php } else { ?>
        <img src="/lazarus/img/client/1_logo.png?id="<?= $random ?> />
      <?php } ?>
    </div>
  </div>



  <main role="main" id="main" class="container">
    <div id="access_denied"><?=$msg_block_noaccess?></div>
      <div id="info_bloqueo">

        <div class="<?= $permanente == 0 ? "flip-card-container" : "flip-card-container-permanent" ?>">
          <div class="flip-card">

            <div class="card-front">
              <!-- símbolo de prohibido grande -->
              <div id="forbidden_sign">
                <i class="fas fa-times"></i>
              </div>
            </div>

            <div class="card-back">
              <?php /* si no es permanente, calculamos temporal */ ?>
              <div>
                <i id="forbidden_sign_timer" class="fas fa-times"></i>
              </div>
              <div>
                <i class="fas fa-hourglass-half"></i> <b><span id="timer">99:99:99</span></b>
              </div>
            </div>

          </div>
        </div>
        <!-- /flip-card-container -->


        <?php
          /*
            <div class="animated_text_container">
              <div class="animated_text"><?=$msg_block_noaccess?></div>
            </div>
          */
        ?>



        <?php if ($bloqueoscreenshots==0){ ?>

          <div>

            <p><?=$msg_block_urlblocked?> <strong><?=$url_data['dominio']?></strong></p>
            <br />

            <?php
              if (($precolor=="1") or ($precolor=="8")){
                $color_bloqueo="success";
              } elseif ($precolor=="2"){
                $color_bloqueo="danger";
              } elseif ($precolor=="9"){
                $color_bloqueo="black";
              } else {
                $color_bloqueo="warning";
              }

              if ($cantdev==0){
                $color_bloqueo="danger";
              }
            ?>
            <div class="bloqueo <?=$color_bloqueo?>">
              <h4><?=$msg?></h4>
              <b><p style="font-size: 16px;"><?=$msg2?></p></b>

              <?php if ($permanente==0){ ?>

                <form id="controlrefresh" name="controlrefresh" method="post" action="//<?=$url_data['dominio']?>"></form>

                <script type="text/javascript">
                  var counttimer=<?= "$controltimer"; ?>;
                  var countertimer=null;
                  function timer(){
                    counttimer=counttimer-1;
                    if (counttimer <= 0){
                      console.log()
                      clearInterval(countertimer);
//                      location.reload();
//                      window.location.href = window.location.href;
                      //document.getElementById("controlrefresh").submit();
                      $("#controlrefresh").submit();
                      return;
                    }

                    hours = parseInt(counttimer / 3600, 10);
                    minutes = parseInt(counttimer / 60, 10);
                    minutes = parseInt(minutes % 60, 10);
                    seconds = parseInt(counttimer % 60, 10);

                    hours = hours < 10 ? "0" + hours : hours;
                    minutes = minutes < 10 ? "0" + minutes : minutes;
                    seconds = seconds < 10 ? "0" + seconds : seconds;
                    //document.getElementById("timer").innerHTML=hours + ":" + minutes + ":" + seconds; // watch for spelling
                    $("#timer").html(hours + ":" + minutes + ":" + seconds); // watch for spelling
                  }

                  setInterval(timer, 1000); //1000 will  run it every 1 second

                  setTimeout(function() {
                    $(".flip-card-container").addClass("show_back");
                  }, 3 * 1000);
                </script>
              <?php } ?>
            </div>
          </div>

          <br />
          <br />
          <div>
            <?=$msg_block_request?>
            <?php if ($envio_activo){ ?>
              <button id="aviso_admin" type="button" class="btn" style="" onclick="alert('deberías saber que usuario es por la IP virtual, que dominio se ha pedido, etc');" ><?=$btn_block_request?></button>
            <?php } ?>
            <?php if ($dev_config['unlock_request']==1) { ?>
              <div class="mt-3">
                <label for="unlock_comment" class="form-label" style="font-weight:600;">
                  <?= isset($lbl_unlock_comment) ? $lbl_unlock_comment : '' ?>
                </label> 
                <textarea
                  id="unlock_comment"
                  name="unlock_comment"
                  class="form-control"
                  rows="3"
                  maxlength="500"
                  placeholder="<?= isset($ph_unlock_comment) ? $ph_unlock_comment : '' ?>"
                ></textarea>
              </div>
              <button
                  id="unlock_button"
                  type="button"
                  class="btn btn-primary mt-3"
                >
                <?=$btn_unlock_request?>
              </button>
              <?php
                if ($isDev) {
                  // Mostrar datos adicionales para desarrollo
                  echo "<pre style='background: #f0f0f0; padding: 10px; margin-top: 20px;'>";
                  echo "DEBUG INFO (VISIBLE SOLO EN DEV):\n";
                  echo "URL: " . ($preurl ?? '') . "\n";
                  echo "Device ID: " . ($dev_info['id'] ?? '') . "\n";
                  echo "Supervisor UUID: " . ($supervisor_uuid ?? '') . "\n";
                  echo "Política: " . ($politica ?? '') . "\n";
                  echo "</pre>";
                  ?>
                  <div class="debug-error-dev"></div>
                  <?php
                }
              ?>
            <?php } ?>
          </div>
          <br>
          <br>
        <?php } else { ?>
          <div>

            <p><?=$msg_block_urlblocked?></p>
            <br />

            <div class="bloqueo blue" disabled>
              <h4><?=$msg_block_screen?></h4>
            </div>
          </div>

          <br>
          <br>

        <?php } ?>

      </div><!-- fin pagina_bloqueo !-->
    </div>
  </main>


  <div id="waves_container">
    <!--Waves Container-->
    <div>
      <svg class="waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
      viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
      <defs>
      <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z" />
      </defs>
      <g class="parallax">
        <use xlink:href="#gentle-wave" x="48" y="0" fill="rgba(79,139,203,1)" />
        <use xlink:href="#gentle-wave" x="48" y="3" fill="rgba(95,155,219,1)" />
        <use xlink:href="#gentle-wave" x="48" y="5" fill="rgba(114,162,213,1)" />
        <use xlink:href="#gentle-wave" x="48" y="7" fill="rgba(149,185,223,1)" />
        <use xlink:href="#gentle-wave" x="48" y="10" fill="rgba(184,208,234,1)" />
      </g>
      </svg>
    </div>
    <!--Waves end-->
  </div>
  <!--Header ends-->

<?php
  //print_footer($generalconfig);
?>
  <script>
    $(function() {
      //alert("JS funcionando");
    });
  </script>

  <script>

    // Funciones Debug

    function logDebugError(message) {
      let debugErrorDevDiv = $(".debug-error-dev");
      if (debugErrorDevDiv.length > 0) {
        const timestamp = new Date().toISOString();
        debugErrorDevDiv.append(`<div style="color: red; margin-bottom: 5px;">[${timestamp}] ${message}</div>`);
      }

    }
          
    //----------------

    (function($){
      $(function(){
        // Flag para evitar enviar la solicitud dos veces si se hace doble clic
        var unlockSubmitting = false;

        function showError() {
          if (typeof Swal !== 'undefined') {
            Swal.fire({ icon: 'error', title: 'Error' });
          } else {
            // Si no está SweetAlert2, usamos el alert nativo del navegador
            alert('Error');
          }
        }

        // Escuchamos el clic en el botón de “enviar solicitud de desbloqueo”
        $(document).on('click', '#unlock_button', function(){
          // Si ya se está enviando, no hacemos nada para evitar envíos duplicados
          if (unlockSubmitting) return;
          // Marcamos que estamos enviando para bloquear nuevos clics
          unlockSubmitting = true;

          // Guardamos una referencia al botón y lo deshabilitamos mientras se envía
          var $btn = $(this).prop('disabled', true);
          // Leemos el comentario del textarea y quitamos espacios sobrantes
          var comment = ($('#unlock_comment').val() || '').trim();

          // Obtenemos la URL
          var url = <?= json_encode($preurl ?? '') ?>;
          // limitamos la URL a 250 caracteres
          if (url.length > 250) url = url.slice(0, 250);

          logDebugError("Enviando solicitud de desbloqueo. URL: " + url + ", Comentario: " + comment);

          $.post('<?= $url_absoluta ?>lazarus/system/eng-requests-center/index.php', {
            datamode: 'create',
            dispositivo: <?= (int)$dev_info['id'] ?>,
            // ID del supervisor que APLICA el filtro que está bloqueando (supervisor_uuid)
            supervisor_uuid: '<?=$supervisor_uuid?>',
            // ID del filtro que está bloqueando (política aplicada)
            filtro: <?= (int)($politica ?? 0) ?>,
            url: <?= json_encode($preurl ?? '') ?>,
            comentario: ($('#unlock_comment').val() || '').trim()

          }, function(r){
            logDebugError("Respuesta del servidor: " + JSON.stringify(r));

            if (r && r.status === 'ok') {
              // Cambiamos el texto del botón para informar que se envió
              $btn.text(<?= json_encode($btn_unlock_sent) ?>); 
              // Bloqueamos el textarea para que no puedan seguir editando
              $('#unlock_comment').prop('disabled', true);

            } else {
              showError();
              $btn.prop('disabled', false);
              unlockSubmitting = false;
            }
          }, 'json').fail(function(error){
            logDebugError("Error en la solicitud AJAX: " + error.status + " " + error.statusText + " - " + error.responseText);
            
            // Mostramos un error genérico
            showError();
            $btn.prop('disabled', false);
            unlockSubmitting = false;
          });
        });
      });
    // Pasamos jQuery (o $) al IIFE para asegurar el alias $
    })(window.jQuery || $);
  </script>


<?php
  print_html_end();
//  <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>
?>
