<?php
@session_start();
require __DIR__ . '/db.php';

$pdo = pdo();

// Si querés ver errores mientras probamos:
ini_set('display_errors', 1);
error_reporting(E_ALL);

/* Aseguramos la tabla de comentarios (sin created_at, como la tuya) */
$pdo->exec("
    CREATE TABLE IF NOT EXISTS noticias_comentarios (
      id INT AUTO_INCREMENT PRIMARY KEY,
      noticia_id INT NOT NULL,
      nombre VARCHAR(255) NOT NULL,
      email VARCHAR(255) NOT NULL,
      web VARCHAR(255) DEFAULT NULL,
      comentario TEXT NOT NULL,
      estado TINYINT(1) NOT NULL DEFAULT 0,
      INDEX (noticia_id),
      INDEX (estado)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

try {
    // por si en algún servidor viejo no existía "estado"
    $pdo->exec("ALTER TABLE noticias_comentarios ADD COLUMN estado TINYINT(1) NOT NULL DEFAULT 0");
} catch (Throwable $e) {
    // ya existe, seguimos
}

/* Acciones aprobar / rechazar / eliminar */
$action = isset($_GET['action']) ? $_GET['action'] : '';
$id     = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id && in_array($action, array('aprobar','rechazar','eliminar'), true)) {

    if ($action === 'aprobar') {
        $st = $pdo->prepare("UPDATE noticias_comentarios SET estado=1 WHERE id=?");
        $st->execute(array($id));
    } elseif ($action === 'rechazar') {
        $st = $pdo->prepare("UPDATE noticias_comentarios SET estado=2 WHERE id=?");
        $st->execute(array($id));
    } elseif ($action === 'eliminar') {
        $st = $pdo->prepare("DELETE FROM noticias_comentarios WHERE id=?");
        $st->execute(array($id));
    }

    header('Location: admin_comentarios.php');
    exit;
}

/* Helper para limpiar texto */
function norm_text_admin($html) {
    $text = strip_tags((string)$html);
    $text = preg_replace('/\xC2\xA0|&nbsp;/u', ' ', $text);
    $text = preg_replace('/\s+/u', ' ', $text);
    return trim($text);
}

/* Deducir título de la nota a partir de titulo o contenido_json */
function build_nota_title_admin($row) {
    $id_nota   = isset($row['noticia_id']) ? (int)$row['noticia_id'] : 0;
    $titulo_bd = trim(isset($row['titulo']) ? $row['titulo'] : '');

    // Si ya hay título real, lo usamos
    if ($titulo_bd !== '' && $titulo_bd !== 'Sin título') {
        return $titulo_bd;
    }

    // Intentamos leer primer H1 del contenido_json
    $contenido_json = isset($row['contenido_json']) ? $row['contenido_json'] : '';
    if ($contenido_json !== '') {
        $blocks = array();
        try {
            $tmp = json_decode($contenido_json, true);
            if (is_array($tmp)) {
                $blocks = $tmp;
            }
        } catch (Throwable $e) {
            $blocks = array();
        }

        if ($blocks) {
            foreach ($blocks as $b) {
                if (isset($b['type']) && $b['type'] === 'h1') {
                    $txt = norm_text_admin(isset($b['content']) ? $b['content'] : '');
                    if ($txt !== '') {
                        return $txt;
                    }
                }
            }
        }
    }

    // Fallback final
    if ($id_nota > 0) {
        return 'Nota #'.$id_nota;
    }
    return 'Sin nota';
}

/* Traer comentarios + datos de la nota
   OJO: ordenamos por c.id DESC, nada de created_at.
*/
$sql = "
    SELECT
        c.*,
        n.titulo,
        n.contenido_json
    FROM noticias_comentarios c
    LEFT JOIN noticias n ON n.id = c.noticia_id
    ORDER BY c.id DESC
";
$stmt = $pdo->query($sql);
$comentarios = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pendientes = (int)$pdo->query("SELECT COUNT(*) FROM noticias_comentarios WHERE estado=0")->fetchColumn();
$aprobados = (int)$pdo->query("SELECT COUNT(*) FROM noticias_comentarios WHERE estado=1")->fetchColumn();
$rechazados = (int)$pdo->query("SELECT COUNT(*) FROM noticias_comentarios WHERE estado=2")->fetchColumn();
$total = count($comentarios);
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Panel de Comentarios</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
  :root {
    --primary: #4361ee;
    --secondary: #3f37c9;
    --success: #4cc9f0;
    --danger: #f72585;
    --warning: #f8961e;
    --info: #4895ef;
    --light: #f8f9fa;
    --dark: #212529;
    --gray: #6c757d;
    --light-bg: #f5f7fb;
    --card-shadow: 0 4px 6px rgba(0, 0, 0, 0.07);
    --hover-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
  }
  
  body {
    background: linear-gradient(135deg, #f5f7fb 0%, #e4e8f5 100%);
    font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
    min-height: 100vh;
    padding-top: 20px;
    padding-bottom: 40px;
  }
  
  .admin-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 20px;
  }
  
  .admin-header {
    background: white;
    border-radius: 16px;
    padding: 24px 30px;
    box-shadow: var(--card-shadow);
    margin-bottom: 30px;
    border-left: 5px solid var(--primary);
  }
  
  .admin-title {
    font-weight: 700;
    color: var(--dark);
    margin: 0;
    font-size: 28px;
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .admin-title i {
    color: var(--primary);
  }
  
  .stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
  }
  
  .stat-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: var(--card-shadow);
    transition: transform 0.3s, box-shadow 0.3s;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .stat-card:hover {
    transform: translateY(-5px);
    box-shadow: var(--hover-shadow);
  }
  
  .stat-card.pending {
    border-top: 4px solid var(--warning);
  }
  
  .stat-card.approved {
    border-top: 4px solid var(--success);
  }
  
  .stat-card.rejected {
    border-top: 4px solid var(--danger);
  }
  
  .stat-card.total {
    border-top: 4px solid var(--primary);
  }
  
  .stat-number {
    font-size: 32px;
    font-weight: 700;
    margin-bottom: 5px;
  }
  
  .stat-label {
    font-size: 14px;
    color: var(--gray);
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }
  
  .comment-card {
    background: white;
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 20px;
    box-shadow: var(--card-shadow);
    transition: all 0.3s ease;
    border-left: 4px solid transparent;
  }
  
  .comment-card:hover {
    box-shadow: var(--hover-shadow);
    transform: translateY(-2px);
  }
  
  .comment-card.pending {
    border-left-color: var(--warning);
  }
  
  .comment-card.approved {
    border-left-color: var(--success);
  }
  
  .comment-card.rejected {
    border-left-color: var(--danger);
  }
  
  .comment-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .comment-meta {
    display: flex;
    flex-direction: column;
  }
  
  .comment-author {
    font-weight: 600;
    font-size: 18px;
    color: var(--dark);
    margin-bottom: 5px;
  }
  
  .comment-email {
    color: var(--gray);
    font-size: 14px;
    margin-bottom: 5px;
  }
  
  .comment-article {
    font-weight: 500;
    color: var(--primary);
    text-decoration: none;
    transition: color 0.2s;
  }
  
  .comment-article:hover {
    color: var(--secondary);
    text-decoration: underline;
  }
  
  .comment-status {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 13px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }
  
  .status-pending {
    background: rgba(248, 150, 30, 0.1);
    color: var(--warning);
  }
  
  .status-approved {
    background: rgba(76, 201, 240, 0.1);
    color: var(--success);
  }
  
  .status-rejected {
    background: rgba(247, 37, 133, 0.1);
    color: var(--danger);
  }
  
  .comment-content {
    background: var(--light-bg);
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 20px;
    line-height: 1.6;
    color: var(--dark);
  }
  
  .comment-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }
  
  .btn-action {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 8px 16px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 14px;
    transition: all 0.2s;
    text-decoration: none;
  }
  
  .btn-approve {
    background: var(--success);
    color: white;
    border: none;
  }
  
  .btn-approve:hover {
    background: #3ab0d9;
    color: white;
    transform: translateY(-2px);
  }
  
  .btn-reject {
    background: white;
    color: var(--danger);
    border: 1px solid var(--danger);
  }
  
  .btn-reject:hover {
    background: var(--danger);
    color: white;
    transform: translateY(-2px);
  }
  
  .btn-delete {
    background: white;
    color: var(--gray);
    border: 1px solid var(--gray);
  }
  
  .btn-delete:hover {
    background: var(--gray);
    color: white;
    transform: translateY(-2px);
  }
  
  .empty-state {
    text-align: center;
    padding: 60px 20px;
    background: white;
    border-radius: 16px;
    box-shadow: var(--card-shadow);
  }
  
  .empty-state i {
    font-size: 64px;
    color: #dee2e6;
    margin-bottom: 20px;
  }
  
  .empty-state h3 {
    color: var(--gray);
    margin-bottom: 10px;
  }
  
  .empty-state p {
    color: var(--gray);
    max-width: 400px;
    margin: 0 auto;
  }
  
  @media (max-width: 768px) {
    .comment-header {
      flex-direction: column;
      align-items: flex-start;
    }
    
    .comment-actions {
      width: 100%;
      justify-content: flex-start;
    }
    
    .admin-title {
      font-size: 24px;
    }
    
    .stats-container {
      grid-template-columns: 1fr 1fr;
    }
  }
  
  @media (max-width: 576px) {
    .stats-container {
      grid-template-columns: 1fr;
    }
    
    .comment-actions {
      flex-direction: column;
      width: 100%;
    }
    
    .btn-action {
      width: 100%;
      justify-content: center;
    }
  }
</style>
</head>
<body>
<div class="admin-container">
  <div class="admin-header">
    <h1 class="admin-title">
      <i class="fas fa-comments"></i>
      Panel de Comentarios
    </h1>
  </div>
  
  <div class="stats-container">
    <div class="stat-card total">
      <div class="stat-number"><?= $total ?></div>
      <div class="stat-label">Total Comentarios</div>
    </div>
    <div class="stat-card pending">
      <div class="stat-number"><?= $pendientes ?></div>
      <div class="stat-label">Pendientes</div>
    </div>
    <div class="stat-card approved">
      <div class="stat-number"><?= $aprobados ?></div>
      <div class="stat-label">Aprobados</div>
    </div>
    <div class="stat-card rejected">
      <div class="stat-number"><?= $rechazados ?></div>
      <div class="stat-label">Rechazados</div>
    </div>
  </div>

  <?php if (empty($comentarios)): ?>
    <div class="empty-state">
      <i class="fas fa-inbox"></i>
      <h3>No hay comentarios</h3>
      <p>No se han encontrado comentarios para mostrar en este momento.</p>
    </div>
  <?php else: ?>
    <div class="comments-list">
      <?php foreach ($comentarios as $i => $c):
          $titulo_nota = build_nota_title_admin($c);
          $url_nota    = 'nota.php?id='.(int)$c['noticia_id'];
          $status_class = '';
          $status_text = '';
          $status_icon = '';
          
          if ((int)$c['estado'] === 0) {
            $status_class = 'pending';
            $status_text = 'Pendiente';
            $status_icon = 'clock';
          } elseif ((int)$c['estado'] === 1) {
            $status_class = 'approved';
            $status_text = 'Aprobado';
            $status_icon = 'check-circle';
          } else {
            $status_class = 'rejected';
            $status_text = 'Rechazado';
            $status_icon = 'times-circle';
          }
      ?>
        <div class="comment-card <?= $status_class ?>">
          <div class="comment-header">
            <div class="comment-meta">
              <div class="comment-author"><?= htmlspecialchars($c['nombre'], ENT_QUOTES, 'UTF-8') ?></div>
              <div class="comment-email"><?= htmlspecialchars($c['email'], ENT_QUOTES, 'UTF-8') ?></div>
              <?php if (!empty($c['noticia_id'])): ?>
                <a href="<?= htmlspecialchars($url_nota, ENT_QUOTES, 'UTF-8') ?>" target="_blank" class="comment-article">
                  <i class="fas fa-newspaper me-1"></i>
                  <?= htmlspecialchars($titulo_nota, ENT_QUOTES, 'UTF-8') ?>
                </a>
              <?php else: ?>
                <span class="text-muted"><i class="fas fa-newspaper me-1"></i>Sin nota asociada</span>
              <?php endif; ?>
            </div>
            <span class="comment-status status-<?= $status_class ?>">
              <i class="fas fa-<?= $status_icon ?>"></i>
              <?= $status_text ?>
            </span>
          </div>
          
          <div class="comment-content">
            <?= nl2br(htmlspecialchars($c['comentario'], ENT_QUOTES, 'UTF-8')) ?>
          </div>
          
          <div class="comment-actions">
            <?php if ((int)$c['estado'] !== 1): ?>
              <a class="btn-action btn-approve" href="admin_comentarios.php?action=aprobar&id=<?= (int)$c['id'] ?>">
                <i class="fas fa-check"></i>
                Aprobar
              </a>
            <?php endif; ?>
            <?php if ((int)$c['estado'] !== 2): ?>
              <a class="btn-action btn-reject" href="admin_comentarios.php?action=rechazar&id=<?= (int)$c['id'] ?>">
                <i class="fas fa-times"></i>
                Rechazar
              </a>
            <?php endif; ?>
            <a class="btn-action btn-delete" 
               href="admin_comentarios.php?action=eliminar&id=<?= (int)$c['id'] ?>"
               onclick="return confirm('¿Estás seguro de que deseas eliminar este comentario?');">
              <i class="fas fa-trash"></i>
              Eliminar
            </a>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>

<script>
// Efecto sutil de aparición para las tarjetas
document.addEventListener('DOMContentLoaded', function() {
  const cards = document.querySelectorAll('.comment-card');
  cards.forEach((card, index) => {
    card.style.opacity = '0';
    card.style.transform = 'translateY(20px)';
    
    setTimeout(() => {
      card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
      card.style.opacity = '1';
      card.style.transform = 'translateY(0)';
    }, index * 100);
  });
});
</script>
</body>
</html>