<?php
// iframe_chat.php - VERSIÓN MEJORADA
// Muestra últimos 15 mensajes con soporte para imágenes, audios, videos, documentos y stickers
require_once __DIR__ . '/config.php';
$pdo = db();

if (session_status() === PHP_SESSION_NONE) { session_start(); }

header('Content-Type: text/html; charset=utf-8');

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$cid = isset($_GET['contacto_id']) ? (int)$_GET['contacto_id'] : 0;

if ($cid <= 0) {
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body style='font-family:Arial; font-size:13px; color:#555;'>Sin contacto</body></html>";
    exit;
}

// Obtener últimos 15 mensajes
$stmt = $pdo->prepare("
    SELECT direccion, tipo, mensaje, fecha, archivo_url
    FROM charlas
    WHERE contacto_id = ?
    ORDER BY fecha DESC, id DESC
    LIMIT 15
");
$stmt->execute([$cid]);
$msgs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$msgs = array_reverse($msgs); // Orden cronológico (viejo → nuevo)
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    html, body { 
      height: 100%; 
      margin: 0;
      overflow: hidden;
    }
    body { 
      padding: 10px; 
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      background: #e5ddd5;
      background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAGklEQVQYlWNgYGD4T0VgYGBgYGBgYKAqmBYAAHoYBAKCqz9gAAAAAElFTkSuQmCC');
      overflow-y: auto;
      overflow-x: hidden;
    }
    
    .wrap { 
      display: flex; 
      flex-direction: column; 
      gap: 8px; 
      padding-bottom: 10px;
    }
    
    .msg {
      max-width: 75%;
      padding: 6px 8px;
      border-radius: 8px;
      font-size: 14px;
      line-height: 1.4;
      word-wrap: break-word;
      position: relative;
      box-shadow: 0 1px 0.5px rgba(0, 0, 0, 0.13);
    }
    
    .enviado { 
      margin-left: auto; 
      background: #d9fdd3;
      border-radius: 8px 0 8px 8px;
    }
    
    .recibido { 
      margin-right: auto; 
      background: #fff;
      border-radius: 0 8px 8px 8px;
    }
    
    .msgContent {
      margin-bottom: 2px;
    }
    
    .meta { 
      font-size: 11px; 
      color: rgba(0, 0, 0, 0.45);
      margin-top: 4px; 
      text-align: right; 
      font-weight: 400;
      user-select: none;
    }
    
    /* IMÁGENES */
    .msgImage {
      border-radius: 8px;
      overflow: hidden;
      margin: 4px 0;
      background: #f0f0f0;
      position: relative;
    }
    
    .msgImage img {
      display: block;
      max-width: 100%;
      height: auto;
      max-height: 300px;
      width: auto;
      cursor: pointer;
      transition: opacity 0.2s;
    }
    
    .msgImage img:hover {
      opacity: 0.9;
    }
    
    .msgImageLoading {
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 120px;
      background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
      background-size: 200% 100%;
      animation: shimmer 1.5s infinite;
    }
    
    @keyframes shimmer {
      0% { background-position: 200% 0; }
      100% { background-position: -200% 0; }
    }
    
    /* AUDIO */
    .msgAudio {
      background: rgba(0, 0, 0, 0.05);
      border-radius: 20px;
      padding: 8px 12px;
      display: flex;
      align-items: center;
      gap: 10px;
      margin: 4px 0;
      min-width: 200px;
    }
    
    .audioPlayBtn {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: #00a884;
      border: none;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      transition: background 0.2s;
    }
    
    .audioPlayBtn:hover {
      background: #008069;
    }
    
    .audioPlayBtn::before {
      content: '';
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 8px 0 8px 14px;
      border-color: transparent transparent transparent white;
      margin-left: 3px;
    }
    
    .audioPlayBtn.playing::before {
      border-style: double;
      border-width: 0 0 0 14px;
      margin-left: 0;
    }
    
    .audioWave {
      flex: 1;
      height: 24px;
      display: flex;
      align-items: center;
      gap: 2px;
    }
    
    .audioBar {
      width: 3px;
      height: 100%;
      background: rgba(0, 0, 0, 0.2);
      border-radius: 2px;
      animation: wave 1.2s ease-in-out infinite;
    }
    
    .audioBar:nth-child(1) { animation-delay: 0s; height: 40%; }
    .audioBar:nth-child(2) { animation-delay: 0.1s; height: 60%; }
    .audioBar:nth-child(3) { animation-delay: 0.2s; height: 80%; }
    .audioBar:nth-child(4) { animation-delay: 0.3s; height: 90%; }
    .audioBar:nth-child(5) { animation-delay: 0.4s; height: 70%; }
    .audioBar:nth-child(6) { animation-delay: 0.5s; height: 85%; }
    .audioBar:nth-child(7) { animation-delay: 0.6s; height: 95%; }
    .audioBar:nth-child(8) { animation-delay: 0.7s; height: 75%; }
    .audioBar:nth-child(9) { animation-delay: 0.8s; height: 55%; }
    .audioBar:nth-child(10) { animation-delay: 0.9s; height: 65%; }
    
    @keyframes wave {
      0%, 100% { transform: scaleY(0.5); }
      50% { transform: scaleY(1); }
    }
    
    .audioDuration {
      font-size: 12px;
      color: rgba(0, 0, 0, 0.5);
      font-weight: 500;
      white-space: nowrap;
    }
    
    /* VIDEO */
    .msgVideo {
      border-radius: 8px;
      overflow: hidden;
      margin: 4px 0;
      background: #000;
      position: relative;
    }
    
    .msgVideo video {
      display: block;
      max-width: 100%;
      height: auto;
      max-height: 300px;
      width: 100%;
    }
    
    .videoPlayOverlay {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 60px;
      height: 60px;
      background: rgba(0, 0, 0, 0.7);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      pointer-events: none;
    }
    
    .videoPlayOverlay::before {
      content: '';
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 12px 0 12px 20px;
      border-color: transparent transparent transparent white;
      margin-left: 4px;
    }
    
    /* DOCUMENTO / ARCHIVO */
    .msgDoc {
      background: rgba(0, 0, 0, 0.05);
      border-radius: 8px;
      padding: 10px 12px;
      display: flex;
      align-items: center;
      gap: 12px;
      margin: 4px 0;
      cursor: pointer;
      transition: background 0.2s;
    }
    
    .msgDoc:hover {
      background: rgba(0, 0, 0, 0.08);
    }
    
    .docIcon {
      width: 40px;
      height: 40px;
      background: #00a884;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      font-size: 20px;
    }
    
    .docInfo {
      flex: 1;
      min-width: 0;
    }
    
    .docName {
      font-size: 13px;
      font-weight: 500;
      color: #111;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .docSize {
      font-size: 12px;
      color: rgba(0, 0, 0, 0.5);
      margin-top: 2px;
    }
    
    /* STICKER */
    .msgSticker {
      background: transparent !important;
      box-shadow: none !important;
      padding: 0 !important;
    }
    
    .msgSticker img {
      display: block;
      width: 120px;
      height: 120px;
      object-fit: contain;
    }
    
    /* UBICACIÓN */
    .msgLocation {
      border-radius: 8px;
      overflow: hidden;
      margin: 4px 0;
      background: #f0f0f0;
    }
    
    .msgLocation img {
      display: block;
      width: 100%;
      height: auto;
      max-height: 200px;
      object-fit: cover;
    }
    
    .locationInfo {
      padding: 8px 10px;
      background: rgba(0, 0, 0, 0.03);
    }
    
    .locationName {
      font-size: 13px;
      font-weight: 500;
      color: #111;
      margin-bottom: 2px;
    }
    
    .locationAddress {
      font-size: 12px;
      color: rgba(0, 0, 0, 0.5);
    }
    
    /* CONTACTO */
    .msgContact {
      background: rgba(0, 0, 0, 0.05);
      border-radius: 8px;
      padding: 10px 12px;
      display: flex;
      align-items: center;
      gap: 12px;
      margin: 4px 0;
    }
    
    .contactAvatar {
      width: 40px;
      height: 40px;
      background: #00a884;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      font-size: 18px;
      color: white;
      font-weight: 500;
    }
    
    .contactInfo {
      flex: 1;
    }
    
    .contactName {
      font-size: 13px;
      font-weight: 500;
      color: #111;
    }
    
    .contactPhone {
      font-size: 12px;
      color: rgba(0, 0, 0, 0.5);
      margin-top: 2px;
    }
    
    /* TIPO BADGE */
    .typeBadge {
      display: inline-block;
      background: rgba(0, 168, 132, 0.15);
      color: #00a884;
      font-size: 11px;
      font-weight: 600;
      padding: 3px 8px;
      border-radius: 12px;
      margin-bottom: 4px;
      text-transform: uppercase;
      letter-spacing: 0.3px;
    }
    
    /* EMPTY STATE */
    .emptyState {
      text-align: center;
      padding: 40px 20px;
      color: rgba(0, 0, 0, 0.4);
      font-size: 14px;
    }
    
    /* SCROLL ANCHOR */
    #scrollAnchor {
      height: 1px;
      margin-top: -1px;
    }
    
    /* LIGHTBOX PARA IMÁGENES */
    .lightbox {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.95);
      z-index: 9999;
      align-items: center;
      justify-content: center;
      cursor: zoom-out;
    }
    
    .lightbox.show {
      display: flex;
    }
    
    .lightbox img {
      max-width: 95%;
      max-height: 95%;
      object-fit: contain;
    }
    
    .lightboxClose {
      position: absolute;
      top: 20px;
      right: 20px;
      width: 40px;
      height: 40px;
      background: rgba(255, 255, 255, 0.2);
      border: none;
      border-radius: 50%;
      color: white;
      font-size: 24px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: background 0.2s;
    }
    
    .lightboxClose:hover {
      background: rgba(255, 255, 255, 0.3);
    }
  </style>
</head>
<body>
  <div class="wrap" id="chatWrap">
    <?php if (!$msgs): ?>
      <div class="emptyState">
        💬<br>
        No hay mensajes aún
      </div>
    <?php else: ?>
      <?php foreach ($msgs as $m): ?>
        <?php
          $direccion = (string)$m['direccion'];
          $tipo = strtolower((string)$m['tipo']);
          $mensaje = (string)($m['mensaje'] ?? '');
          $archivoUrl = (string)($m['archivo_url'] ?? '');
          
          $claseDir = ($direccion === 'enviado') ? 'enviado' : 'recibido';
          
          $hora = '';
          if (!empty($m['fecha'])) {
              $ts = strtotime($m['fecha']);
              if ($ts) $hora = date('H:i', $ts);
          }
        ?>
        
        <div class="msg <?= $claseDir ?> msg-tipo-<?= h($tipo) ?>">
          
          <?php if ($tipo === 'imagen' || $tipo === 'image'): ?>
            <!-- IMAGEN -->
            <?php if ($archivoUrl): ?>
              <div class="msgImage">
                <img src="<?= h($archivoUrl) ?>" 
                     alt="Imagen" 
                     loading="lazy"
                     onclick="openLightbox('<?= h($archivoUrl) ?>')">
              </div>
            <?php else: ?>
              <div class="msgImageLoading">📷</div>
            <?php endif; ?>
            <?php if ($mensaje): ?>
              <div class="msgContent"><?= nl2br(h($mensaje)) ?></div>
            <?php endif; ?>
            
          <?php elseif ($tipo === 'audio' || $tipo === 'voice' || $tipo === 'ptt'): ?>
            <!-- AUDIO / VOZ -->
            <div class="msgAudio">
              <button class="audioPlayBtn" onclick="toggleAudio(this, '<?= h($archivoUrl) ?>')"></button>
              <div class="audioWave">
                <div class="audioBar"></div>
                <div class="audioBar"></div>
                <div class="audioBar"></div>
                <div class="audioBar"></div>
                <div class="audioBar"></div>
                <div class="audioBar"></div>
                <div class="audioBar"></div>
                <div class="audioBar"></div>
                <div class="audioBar"></div>
                <div class="audioBar"></div>
              </div>
              <div class="audioDuration">0:00</div>
            </div>
            <?php if ($mensaje): ?>
              <div class="msgContent"><?= nl2br(h($mensaje)) ?></div>
            <?php endif; ?>
            
          <?php elseif ($tipo === 'video'): ?>
            <!-- VIDEO -->
            <div class="msgVideo">
              <?php if ($archivoUrl): ?>
                <video controls>
                  <source src="<?= h($archivoUrl) ?>" type="video/mp4">
                  Tu navegador no soporta video.
                </video>
                <div class="videoPlayOverlay"></div>
              <?php else: ?>
                <div style="padding:20px; text-align:center; color:#fff;">🎥 Video</div>
              <?php endif; ?>
            </div>
            <?php if ($mensaje): ?>
              <div class="msgContent"><?= nl2br(h($mensaje)) ?></div>
            <?php endif; ?>
            
          <?php elseif ($tipo === 'sticker'): ?>
            <!-- STICKER -->
            <?php if ($archivoUrl): ?>
              <img src="<?= h($archivoUrl) ?>" alt="Sticker" loading="lazy">
            <?php else: ?>
              <div style="font-size:48px;">😊</div>
            <?php endif; ?>
            
          <?php elseif ($tipo === 'documento' || $tipo === 'document'): ?>
            <!-- DOCUMENTO -->
            <div class="msgDoc" onclick="<?= $archivoUrl ? "window.open('".h($archivoUrl)."', '_blank')" : '' ?>">
              <div class="docIcon">📄</div>
              <div class="docInfo">
                <div class="docName"><?= h($mensaje ?: 'Documento') ?></div>
                <div class="docSize">Archivo adjunto</div>
              </div>
            </div>
            
          <?php elseif ($tipo === 'ubicacion' || $tipo === 'location'): ?>
            <!-- UBICACIÓN -->
            <div class="msgLocation">
              <img src="https://maps.googleapis.com/maps/api/staticmap?center=<?= urlencode($mensaje) ?>&zoom=15&size=300x200&markers=color:red%7C<?= urlencode($mensaje) ?>&key=YOUR_API_KEY" 
                   alt="Ubicación"
                   onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22300%22 height=%22200%22%3E%3Crect fill=%22%23e0e0e0%22 width=%22300%22 height=%22200%22/%3E%3Ctext x=%2250%25%22 y=%2250%25%22 text-anchor=%22middle%22 dy=%22.3em%22 fill=%22%23999%22 font-size=%2220%22%3E📍 Ubicación%3C/text%3E%3C/svg%3E'">
              <div class="locationInfo">
                <div class="locationName">📍 Ubicación compartida</div>
                <?php if ($mensaje): ?>
                  <div class="locationAddress"><?= h($mensaje) ?></div>
                <?php endif; ?>
              </div>
            </div>
            
          <?php elseif ($tipo === 'contacto' || $tipo === 'contact'): ?>
            <!-- CONTACTO -->
            <div class="msgContact">
              <div class="contactAvatar">👤</div>
              <div class="contactInfo">
                <div class="contactName"><?= h($mensaje ?: 'Contacto') ?></div>
                <div class="contactPhone">Contacto compartido</div>
              </div>
            </div>
            
          <?php elseif ($tipo === 'texto' || $tipo === 'text' || !$tipo): ?>
            <!-- TEXTO NORMAL -->
            <div class="msgContent"><?= nl2br(h($mensaje)) ?></div>
            
          <?php else: ?>
            <!-- TIPO DESCONOCIDO -->
            <span class="typeBadge"><?= h($tipo) ?></span>
            <div class="msgContent"><?= nl2br(h($mensaje ?: '(contenido multimedia)')) ?></div>
          <?php endif; ?>
          
          <?php if ($hora): ?>
            <div class="meta"><?= h($hora) ?></div>
          <?php endif; ?>
        </div>
        
      <?php endforeach; ?>
    <?php endif; ?>
    
    <div id="scrollAnchor"></div>
  </div>
  
  <!-- LIGHTBOX PARA IMÁGENES -->
  <div class="lightbox" id="lightbox" onclick="closeLightbox()">
    <button class="lightboxClose" onclick="closeLightbox(); event.stopPropagation();">×</button>
    <img id="lightboxImg" src="" alt="">
  </div>
  
  <script>
    // AUTO-SCROLL AL ÚLTIMO MENSAJE
    function scrollToBottom() {
      const anchor = document.getElementById('scrollAnchor');
      if (anchor) {
        anchor.scrollIntoView({ block: 'end', behavior: 'auto' });
      }
    }
    
    // Múltiples intentos para asegurar scroll (imágenes pueden cambiar altura)
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        setTimeout(scrollToBottom, 50);
        setTimeout(scrollToBottom, 200);
        setTimeout(scrollToBottom, 500);
      });
    } else {
      setTimeout(scrollToBottom, 50);
      setTimeout(scrollToBottom, 200);
      setTimeout(scrollToBottom, 500);
    }
    
    window.addEventListener('load', () => {
      setTimeout(scrollToBottom, 100);
      setTimeout(scrollToBottom, 300);
    });
    
    // Scroll cuando cargan las imágenes
    const images = document.querySelectorAll('img');
    images.forEach(img => {
      img.addEventListener('load', () => {
        setTimeout(scrollToBottom, 50);
      });
    });
    
    // LIGHTBOX PARA IMÁGENES
    function openLightbox(src) {
      const lightbox = document.getElementById('lightbox');
      const img = document.getElementById('lightboxImg');
      img.src = src;
      lightbox.classList.add('show');
    }
    
    function closeLightbox() {
      const lightbox = document.getElementById('lightbox');
      lightbox.classList.remove('show');
    }
    
    // Cerrar lightbox con ESC
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') closeLightbox();
    });
    
    // AUDIO PLAYER
    let currentAudio = null;
    
    function toggleAudio(btn, url) {
      if (!url) {
        alert('Audio no disponible');
        return;
      }
      
      // Si hay audio reproduciéndose, pausarlo
      if (currentAudio && !currentAudio.paused) {
        currentAudio.pause();
        const prevBtn = document.querySelector('.audioPlayBtn.playing');
        if (prevBtn) prevBtn.classList.remove('playing');
      }
      
      // Si es el mismo audio, solo pausar
      if (currentAudio && currentAudio.src === url && !currentAudio.paused) {
        currentAudio.pause();
        btn.classList.remove('playing');
        return;
      }
      
      // Crear nuevo audio o reproducir
      if (!currentAudio || currentAudio.src !== url) {
        currentAudio = new Audio(url);
        
        currentAudio.addEventListener('ended', () => {
          btn.classList.remove('playing');
        });
        
        currentAudio.addEventListener('error', () => {
          alert('Error al cargar el audio');
          btn.classList.remove('playing');
        });
      }
      
      currentAudio.play();
      btn.classList.add('playing');
    }
    
    // VIDEO: Quitar overlay al reproducir
    const videos = document.querySelectorAll('.msgVideo video');
    videos.forEach(video => {
      video.addEventListener('play', function() {
        const overlay = this.nextElementSibling;
        if (overlay && overlay.classList.contains('videoPlayOverlay')) {
          overlay.style.display = 'none';
        }
      });
      
      video.addEventListener('pause', function() {
        const overlay = this.nextElementSibling;
        if (overlay && overlay.classList.contains('videoPlayOverlay')) {
          overlay.style.display = 'flex';
        }
      });
    });
  </script>
</body>
</html>