<?php
session_start();
require_once '../config.php';

// Verificar autenticación
if (!isAuthenticated()) {
  redirect('login.php');
}

// Verificar permisos (admin o director)
if (!hasRole([ROLE_ADMIN, ROLE_DIRECTOR])) {
  http_response_code(403);
  die("<h1>Acceso Denegado (403)</h1><p>Tu rol no tiene permiso para gestionar comunicados.</p>");
}

// Obtener conexión
$mysqli = getDBConnection();

$msg = '';
$tipo_msg = '';
$editando = false;
$comunicado_editar = null;

// Procesar acciones
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $accion = $_POST['accion'] ?? '';
  
  // Crear comunicado
  if ($accion === 'crear' && !empty($_POST['titulo']) && !empty($_POST['contenido'])) {
    $titulo = trim($_POST['titulo']);
    $contenido = trim($_POST['contenido']);
    $categoria = $_POST['categoria'] ?? 'informativo';
    $destacado = isset($_POST['destacado']) ? 1 : 0;
    
    // Si se marca como destacado, quitar destacado a los demás
    if ($destacado == 1) {
      $mysqli->query("UPDATE comunicados SET destacado = 0");
    }
    
    $stmt = $mysqli->prepare("INSERT INTO comunicados (titulo, contenido, categoria, destacado, fecha) VALUES (?, ?, ?, ?, NOW())");
    $stmt->bind_param('sssi', $titulo, $contenido, $categoria, $destacado);
    
    if ($stmt->execute()) {
      $msg = '✅ Comunicado publicado exitosamente.';
      $tipo_msg = 'exito';
      logError("Comunicado creado: $titulo (Categoría: $categoria, Destacado: $destacado)", 'INFO');
    } else {
      $msg = '❌ Error al publicar el comunicado.';
      $tipo_msg = 'error';
      logError("Error al crear comunicado: " . $stmt->error, 'ERROR');
    }
    $stmt->close();
  }
  
  // Actualizar comunicado
  elseif ($accion === 'actualizar' && isset($_POST['id']) && !empty($_POST['titulo']) && !empty($_POST['contenido'])) {
    $id = intval($_POST['id']);
    $titulo = trim($_POST['titulo']);
    $contenido = trim($_POST['contenido']);
    $categoria = $_POST['categoria'] ?? 'informativo';
    $destacado = isset($_POST['destacado']) ? 1 : 0;
    
    // Si se marca como destacado, quitar destacado a los demás
    if ($destacado == 1) {
      $mysqli->query("UPDATE comunicados SET destacado = 0 WHERE id != $id");
    }
    
    $stmt = $mysqli->prepare("UPDATE comunicados SET titulo = ?, contenido = ?, categoria = ?, destacado = ?, updated_at = NOW() WHERE id = ?");
    $stmt->bind_param('sssii', $titulo, $contenido, $categoria, $destacado, $id);
    
    if ($stmt->execute()) {
      $msg = '✅ Comunicado actualizado correctamente.';
      $tipo_msg = 'exito';
      logError("Comunicado actualizado ID: $id", 'INFO');
    } else {
      $msg = '❌ Error al actualizar el comunicado.';
      $tipo_msg = 'error';
      logError("Error al actualizar comunicado: " . $stmt->error, 'ERROR');
    }
    $stmt->close();
  }
  
  // Eliminar comunicado
  elseif ($accion === 'eliminar' && isset($_POST['id'])) {
    $id = intval($_POST['id']);
    $stmt = $mysqli->prepare("DELETE FROM comunicados WHERE id = ?");
    $stmt->bind_param('i', $id);
    
    if ($stmt->execute()) {
      $msg = '🗑️ Comunicado eliminado correctamente.';
      $tipo_msg = 'exito';
      logError("Comunicado eliminado ID: $id", 'INFO');
    } else {
      $msg = '❌ Error al eliminar el comunicado.';
      $tipo_msg = 'error';
      logError("Error al eliminar comunicado: " . $stmt->error, 'ERROR');
    }
    $stmt->close();
  }
  
  // Marcar/desmarcar como destacado
  elseif ($accion === 'toggle_destacado' && isset($_POST['id'])) {
    $id = intval($_POST['id']);
    
    // Primero quitar destacado a todos
    $mysqli->query("UPDATE comunicados SET destacado = 0");
    
    // Marcar este como destacado
    $stmt = $mysqli->prepare("UPDATE comunicados SET destacado = 1 WHERE id = ?");
    $stmt->bind_param('i', $id);
    
    if ($stmt->execute()) {
      $msg = '⭐ Comunicado marcado como destacado.';
      $tipo_msg = 'exito';
    }
    $stmt->close();
  }
  
  elseif ($accion === 'quitar_destacado' && isset($_POST['id'])) {
    $id = intval($_POST['id']);
    $stmt = $mysqli->prepare("UPDATE comunicados SET destacado = 0 WHERE id = ?");
    $stmt->bind_param('i', $id);
    
    if ($stmt->execute()) {
      $msg = 'ℹ️ Destacado removido.';
      $tipo_msg = 'exito';
    }
    $stmt->close();
  }
}

// Modo edición
if (isset($_GET['editar'])) {
  $editando = true;
  $id_editar = intval($_GET['editar']);
  $stmt = $mysqli->prepare("SELECT * FROM comunicados WHERE id = ?");
  $stmt->bind_param('i', $id_editar);
  $stmt->execute();
  $result = $stmt->get_result();
  $comunicado_editar = $result->fetch_assoc();
  $stmt->close();
  
  if (!$comunicado_editar) {
    $msg = '❌ Comunicado no encontrado.';
    $tipo_msg = 'error';
    $editando = false;
  }
}

// Obtener lista de comunicados
$result = $mysqli->query("SELECT * FROM comunicados ORDER BY destacado DESC, fecha DESC");
?>

<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Gestión de Comunicados - <?php echo SITE_NAME; ?></title>
  
  <!-- TinyMCE Editor -->
  <script src="https://cdn.tiny.cloud/1/v4nynpt24sf6ac1r9qkj4i01s080izq86torr9ddkxonpznx/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
  
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background: #f5f9fc;
      padding: 20px;
    }
    
    .container {
      max-width: 1400px;
      margin: 0 auto;
    }
    
    .header {
      background: linear-gradient(135deg, #1976d2 0%, #0288d1 100%);
      color: white;
      padding: 30px;
      border-radius: 8px;
      margin-bottom: 30px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }
    
    .header h1 {
      margin-bottom: 10px;
    }
    
    .header-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 15px;
      margin-top: 15px;
    }
    
    .nav-links a {
      color: #ffc107;
      text-decoration: none;
      margin-right: 20px;
      font-weight: 600;
      transition: all 0.3s;
    }
    
    .nav-links a:hover {
      text-decoration: underline;
    }
    
    .mensaje {
      padding: 20px;
      border-radius: 8px;
      margin-bottom: 25px;
      animation: slideIn 0.5s ease;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    
    .mensaje-exito {
      background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
      color: #2e7d32;
      border-left: 5px solid #4caf50;
    }
    
    .mensaje-error {
      background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
      color: #c62828;
      border-left: 5px solid #f44336;
    }
    
    @keyframes slideIn {
      from {
        opacity: 0;
        transform: translateY(-20px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
    
    .card {
      background: white;
      padding: 30px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      margin-bottom: 30px;
    }
    
    .card h2 {
      color: #1976d2;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 3px solid #e3f2fd;
    }
    
    .form-group {
      margin-bottom: 20px;
    }
    
    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 600;
      color: #333;
    }
    
    input[type="text"] {
      width: 100%;
      padding: 12px 15px;
      border: 2px solid #e0e0e0;
      border-radius: 8px;
      font-size: 1em;
      font-family: inherit;
      transition: all 0.3s;
    }
    
    input:focus {
      outline: none;
      border-color: #1976d2;
      box-shadow: 0 0 0 3px rgba(25, 118, 210, 0.1);
    }
    
    select {
      width: 100%;
      padding: 12px 15px;
      border: 2px solid #e0e0e0;
      border-radius: 8px;
      font-size: 1em;
      font-family: inherit;
      transition: all 0.3s;
      background: white;
    }
    
    select:focus {
      outline: none;
      border-color: #1976d2;
      box-shadow: 0 0 0 3px rgba(25, 118, 210, 0.1);
    }
    
    .checkbox-group {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 15px;
      background: #fff8f0;
      border: 2px solid #ffc107;
      border-radius: 8px;
      margin-top: 15px;
    }
    
    .checkbox-group input[type="checkbox"] {
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
    
    .checkbox-group label {
      margin: 0;
      cursor: pointer;
      flex: 1;
    }
    
    .btn {
      padding: 12px 24px;
      border: none;
      border-radius: 50px;
      font-size: 1em;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }
    
    .btn-primary {
      background: linear-gradient(135deg, #1976d2 0%, #0288d1 100%);
      color: white;
      box-shadow: 0 4px 15px rgba(25, 118, 210, 0.3);
    }
    
    .btn-primary:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(25, 118, 210, 0.4);
    }
    
    .btn-success {
      background: linear-gradient(135deg, #4caf50 0%, #388e3c 100%);
      color: white;
      box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
      padding: 8px 16px;
      font-size: 0.9em;
    }
    
    .btn-danger {
      background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
      color: white;
      box-shadow: 0 4px 15px rgba(244, 67, 54, 0.3);
      padding: 8px 16px;
      font-size: 0.9em;
    }
    
    .btn-secondary {
      background: #9e9e9e;
      color: white;
      padding: 8px 16px;
      font-size: 0.9em;
    }
    
    .btn-warning {
      background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
      color: white;
      padding: 8px 16px;
      font-size: 0.9em;
    }
    
    .comunicados-lista {
      display: grid;
      gap: 20px;
    }
    
    .comunicado-item {
      background: white;
      padding: 25px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      border-left: 5px solid #1976d2;
      transition: all 0.3s;
      position: relative;
    }
    
    .comunicado-item:hover {
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      transform: translateX(5px);
    }
    
    .comunicado-item.destacado {
      border-left-color: #ffc107;
      background: linear-gradient(135deg, #fffef7 0%, #fff8e1 100%);
    }
    
    .badge-destacado-item {
      position: absolute;
      top: -10px;
      right: 20px;
      background: #ffc107;
      color: #333;
      padding: 5px 15px;
      border-radius: 20px;
      font-size: 0.8em;
      font-weight: 700;
      box-shadow: 0 2px 8px rgba(255, 193, 7, 0.4);
    }
    
    .comunicado-header {
      display: flex;
      justify-content: space-between;
      align-items: start;
      margin-bottom: 15px;
      gap: 15px;
    }
    
    .comunicado-titulo {
      color: #1976d2;
      font-size: 1.3em;
      font-weight: 600;
      flex: 1;
    }
    
    .comunicado-meta {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
      margin-bottom: 15px;
    }
    
    .badge {
      padding: 5px 12px;
      border-radius: 20px;
      font-size: 0.85em;
      font-weight: 600;
      text-transform: uppercase;
    }
    
    .badge-importante {
      background: #ffebee;
      color: #c62828;
    }
    
    .badge-informativo {
      background: #e3f2fd;
      color: #1976d2;
    }
    
    .badge-evento {
      background: #f3e5f5;
      color: #7b1fa2;
    }
    
    .badge-urgente {
      background: #f44336;
      color: white;
    }
    
    .comunicado-fecha {
      color: #666;
      font-size: 0.9em;
    }
    
    .comunicado-contenido {
      color: #555;
      line-height: 1.6;
      margin-bottom: 15px;
      padding: 15px;
      background: #fafafa;
      border-radius: 4px;
    }
    
    .comunicado-acciones {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }
    
    .sin-comunicados {
      text-align: center;
      padding: 60px 30px;
      color: #999;
    }
    
    .sin-comunicados-icono {
      font-size: 4em;
      margin-bottom: 20px;
      opacity: 0.3;
    }
    
    .ayuda-editor {
      background: #e3f2fd;
      padding: 15px;
      border-radius: 4px;
      margin-bottom: 15px;
      font-size: 0.9em;
    }
    
    .ayuda-editor summary {
      cursor: pointer;
      font-weight: 600;
      color: #1976d2;
    }
    
    .ayuda-editor ul {
      margin-top: 10px;
      margin-left: 20px;
    }
    
    @media (max-width: 768px) {
      .header-info {
        flex-direction: column;
        align-items: flex-start;
      }
      
      .comunicado-header {
        flex-direction: column;
      }
      
      .comunicado-acciones {
        flex-direction: column;
      }
      
      .btn {
        width: 100%;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>📢 Gestión de Comunicados</h1>
      <div class="header-info">
        <div>
          👤 Usuario: <strong><?php echo sanitize($_SESSION['usuario'] ?? 'Admin'); ?></strong> | 
          🔐 Rol: <strong><?php echo sanitize($_SESSION['rol']); ?></strong>
        </div>
        <div class="nav-links">
          <a href="dashboard.php">📊 Dashboard</a>
          <a href="gestor_contactos.php">📋 Ver Contactos</a>
          <?php if (hasRole([ROLE_ADMIN])): ?>
            <a href="gestor_usuarios.php">👥 Usuarios</a>
          <?php endif; ?>
          <a href="../index.php">🏠 Ver Sitio</a>
          <a href="logout.php">🚪 Cerrar Sesión</a>
        </div>
      </div>
    </div>

    <?php if ($msg): ?>
      <div class="mensaje <?php echo $tipo_msg === 'exito' ? 'mensaje-exito' : 'mensaje-error'; ?>">
        <?php echo sanitize($msg); ?>
      </div>
    <?php endif; ?>

    <!-- Formulario para crear/editar comunicado -->
    <div class="card">
      <h2><?php echo $editando ? '✏️ Editar Comunicado' : '✍️ Publicar Nuevo Comunicado'; ?></h2>
      
      <?php if ($editando): ?>
        <div style="background: #fff3cd; padding: 15px; border-radius: 4px; margin-bottom: 20px;">
          <strong>ℹ️ Modo Edición</strong> - Estás editando el comunicado "<?php echo sanitize($comunicado_editar['titulo']); ?>"
          <a href="admin_comunicados.php" style="margin-left: 15px; color: #1976d2; font-weight: 600;">Cancelar edición</a>
        </div>
      <?php endif; ?>
      
      <!-- Ayuda sobre el editor -->
      <details class="ayuda-editor">
        <summary>💡 Ayuda: Cómo usar el editor HTML</summary>
        <ul>
          <li><strong>Negrita:</strong> Selecciona texto y click en <strong>B</strong></li>
          <li><strong>Cursiva:</strong> Selecciona texto y click en <em>I</em></li>
          <li><strong>Listas:</strong> Usa los botones de lista numerada o con viñetas</li>
          <li><strong>Enlaces:</strong> Selecciona texto y click en el icono de enlace 🔗</li>
          <li><strong>Colores:</strong> Usa el selector de color para destacar texto</li>
          <li><strong>Tablas:</strong> Click en el icono de tabla para insertar</li>
        </ul>
      </details>
      
      <form method="post" action="admin_comunicados.php" autocomplete="off">
        <input type="hidden" name="accion" value="<?php echo $editando ? 'actualizar' : 'crear'; ?>">
        <?php if ($editando): ?>
          <input type="hidden" name="id" value="<?php echo $comunicado_editar['id']; ?>">
        <?php endif; ?>
        
        <div class="form-group">
          <label for="titulo">📝 Título del Comunicado *</label>
          <input type="text" 
                 name="titulo" 
                 id="titulo" 
                 required 
                 placeholder="Ej: Corte de suministro programado"
                 value="<?php echo $editando ? sanitize($comunicado_editar['titulo']) : ''; ?>">
        </div>
        
        <div class="form-group">
          <label for="categoria">🏷️ Categoría *</label>
          <select name="categoria" id="categoria" required>
            <option value="informativo" <?php echo ($editando && $comunicado_editar['categoria'] == 'informativo') ? 'selected' : ''; ?>>
              ℹ️ Informativo (avisos generales, noticias)
            </option>
            <option value="importante" <?php echo ($editando && $comunicado_editar['categoria'] == 'importante') ? 'selected' : ''; ?>>
              ⚠️ Importante (cortes, suspensiones, urgencias)
            </option>
            <option value="evento" <?php echo ($editando && $comunicado_editar['categoria'] == 'evento') ? 'selected' : ''; ?>>
              📅 Evento (asambleas, reuniones, actividades)
            </option>
            <option value="urgente" <?php echo ($editando && $comunicado_editar['categoria'] == 'urgente') ? 'selected' : ''; ?>>
              🚨 Urgente (emergencias, situaciones críticas)
            </option>
          </select>
          <small style="color: #666; display: block; margin-top: 5px;">
            La categoría define el color del badge y la prioridad visual del comunicado
          </small>
        </div>

        <div class="form-group">
          <label for="contenido">📄 Contenido *</label>
          <textarea name="contenido" id="contenido" required><?php echo $editando ? $comunicado_editar['contenido'] : ''; ?></textarea>
        </div>
        
        <div class="checkbox-group">
          <input type="checkbox" 
                 name="destacado" 
                 id="destacado" 
                 value="1"
                 <?php echo ($editando && $comunicado_editar['destacado'] == 1) ? 'checked' : ''; ?>>
          <label for="destacado">
            ⭐ <strong>Marcar como DESTACADO</strong> (aparecerá primero en la página principal y tendrá ribbon dorado)
          </label>
        </div>
        <small style="color: #856404; display: block; margin-top: 10px; padding-left: 15px;">
          💡 Solo puede haber un comunicado destacado a la vez. Si marcas este, el anterior perderá el destacado.
        </small>

        <div style="margin-top: 25px; display: flex; gap: 15px;">
          <button type="submit" class="btn btn-primary">
            <?php echo $editando ? '💾 Guardar Cambios' : '📤 Publicar Comunicado'; ?>
          </button>
          
          <?php if ($editando): ?>
            <a href="admin_comunicados.php" class="btn btn-secondary" style="display: inline-block; text-decoration: none; text-align: center;">
              ❌ Cancelar
            </a>
          <?php endif; ?>
        </div>
      </form>
    </div>

    <!-- Lista de comunicados existentes -->
    <div class="card">
      <h2>📋 Comunicados Publicados (<?php echo $result->num_rows; ?>)</h2>
      
      <?php if ($result && $result->num_rows > 0): ?>
        <div class="comunicados-lista">
          <?php while ($row = $result->fetch_assoc()): ?>
            <div class="comunicado-item <?php echo $row['destacado'] == 1 ? 'destacado' : ''; ?>">
              <?php if ($row['destacado'] == 1): ?>
                <span class="badge-destacado-item">⭐ DESTACADO</span>
              <?php endif; ?>
              
              <div class="comunicado-header">
                <div class="comunicado-titulo"><?php echo sanitize($row['titulo']); ?></div>
              </div>
              
              <div class="comunicado-meta">
                <span class="badge badge-<?php echo $row['categoria']; ?>">
                  <?php 
                  $iconos = [
                    'informativo' => 'ℹ️',
                    'importante' => '⚠️',
                    'evento' => '📅',
                    'urgente' => '🚨'
                  ];
                  echo $iconos[$row['categoria']] . ' ' . strtoupper($row['categoria']); 
                  ?>
                </span>
                <span class="comunicado-fecha">
                  📅 <?php echo date('d/m/Y H:i', strtotime($row['fecha'])); ?>
                </span>
              </div>
              
              <div class="comunicado-contenido">
                <?php echo $row['contenido']; // Ya permite HTML ?>
              </div>
              
              <div class="comunicado-acciones">
                <a href="admin_comunicados.php?editar=<?php echo $row['id']; ?>" class="btn btn-success">
                  ✏️ Editar
                </a>
                
                <?php if ($row['destacado'] == 0): ?>
                  <form method="post" action="admin_comunicados.php" style="display: inline;">
                    <input type="hidden" name="accion" value="toggle_destacado">
                    <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                    <button type="submit" class="btn btn-warning">
                      ⭐ Marcar Destacado
                    </button>
                  </form>
                <?php else: ?>
                  <form method="post" action="admin_comunicados.php" style="display: inline;">
                    <input type="hidden" name="accion" value="quitar_destacado">
                    <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                    <button type="submit" class="btn btn-secondary">
                      ⭐ Quitar Destacado
                    </button>
                  </form>
                <?php endif; ?>
                
                <form method="post" action="admin_comunicados.php" style="display: inline;" onsubmit="return confirm('¿Está seguro de eliminar este comunicado? Esta acción no se puede deshacer.');">
                  <input type="hidden" name="accion" value="eliminar">
                  <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                  <button type="submit" class="btn btn-danger">
                    🗑️ Eliminar
                  </button>
                </form>
              </div>
            </div>
          <?php endwhile; ?>
        </div>
      <?php else: ?>
        <div class="sin-comunicados">
          <div class="sin-comunicados-icono">📭</div>
          <p>No hay comunicados publicados.</p>
        </div>
      <?php endif; ?>
    </div>
  </div>
  
  <script>
    // Inicializar TinyMCE
    tinymce.init({
      selector: '#contenido',
      height: 400,
      menubar: false,
      language: 'es',
      plugins: [
        'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
        'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
        'insertdatetime', 'media', 'table', 'help', 'wordcount'
      ],
      toolbar: 'undo redo | formatselect | ' +
               'bold italic underline strikethrough | forecolor backcolor | ' +
               'alignleft aligncenter alignright alignjustify | ' +
               'bullist numlist outdent indent | ' +
               'link image | removeformat | help',
      content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 14px; line-height: 1.6; }',
      
      // Configuración en español
      language_url: 'https://cdn.tiny.cloud/1/v4nynpt24sf6ac1r9qkj4i01s080izq86torr9ddkxonpznx/tinymce/6/langs/es.js',
      
      // Permitir todos los elementos HTML
      valid_elements: '*[*]',
      extended_valid_elements: '*[*]',
      
      // Configuración de imagen
      image_advtab: true,
      file_picker_types: 'image',
      
      // Configuración de tabla
      table_default_attributes: {
        border: '1'
      },
      table_default_styles: {
        'border-collapse': 'collapse',
        'width': '100%'
      }
    });
  </script>
</body>
</html>
