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

$pdo = pdo();
$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT * FROM noticias WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$N = $stmt->fetch();
if (!$N) { http_response_code(404); echo "Noticia no encontrada"; exit; }

/* =========================
   COMENTARIOS: guardar + leer
   ========================= */

// aseguro que la tabla tenga el campo estado (0=pendiente,1=aprobado,2=rechazado)
$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,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      INDEX (noticia_id),
      INDEX (estado)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");
try {
    // por si la tabla ya existía sin el campo estado (no pasa nada si ya existe)
    $pdo->exec("ALTER TABLE noticias_comentarios ADD COLUMN estado TINYINT(1) NOT NULL DEFAULT 0");
} catch (Throwable $e) {
    // ignoramos el error si ya existe
}

$comentario_ok  = !empty($_SESSION['comentario_ok']);
$comentario_err = $_SESSION['comentario_err'] ?? [];
unset($_SESSION['comentario_ok'], $_SESSION['comentario_err']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['comentario'])) {
    $comentario = trim($_POST['comentario'] ?? '');
    $nombre     = trim($_POST['nombre'] ?? '');
    $email      = trim($_POST['email'] ?? '');
    $web        = trim($_POST['web'] ?? '');

    $errores = [];
    if ($comentario === '') $errores[] = 'El comentario es obligatorio.';
    if ($nombre === '')     $errores[] = 'El nombre es obligatorio.';
    if ($email === '')      $errores[] = 'El correo electrónico es obligatorio.';

    if ($errores) {
        $_SESSION['comentario_err'] = $errores;
        $_SESSION['comentario_old'] = [
            'comentario' => $comentario,
            'nombre'     => $nombre,
            'email'      => $email,
            'web'        => $web
        ];
    } else {
        $stmtC = $pdo->prepare("
            INSERT INTO noticias_comentarios (noticia_id, nombre, email, web, comentario, estado)
            VALUES (?,?,?,?,?,0)
        ");
        $stmtC->execute([$id, $nombre, $email, $web, $comentario]);

        $_SESSION['comentario_ok'] = true;
        unset($_SESSION['comentario_old']);

        header('Location: '.$_SERVER['REQUEST_URI']);
        exit;
    }

    header('Location: '.$_SERVER['REQUEST_URI']);
    exit;
}

// solo comentarios APROBADOS (estado=1)
$comentarios = [];
try {
    $stmtC = $pdo->prepare("
        SELECT * FROM noticias_comentarios
        WHERE noticia_id=? AND estado=1
        ORDER BY id DESC
    ");
    $stmtC->execute([$id]);
    $comentarios = $stmtC->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $comentarios = [];
}

// valores viejos si hubo error
$old = $_SESSION['comentario_old'] ?? ['comentario'=>'','nombre'=>'','email'=>'','web'=>''];
unset($_SESSION['comentario_old']);

$blocks = [];
try { $blocks = json_decode($N['contenido_json'], true) ?: []; } catch(Throwable $e){ $blocks=[]; }

function s($v){ return htmlspecialchars($v, ENT_QUOTES, 'UTF-8'); }
function norm_text($t){
  $t = str_replace(["\xC2\xA0",'&nbsp;'], ' ', (string)$t);
  $t = strip_tags($t);
  $t = preg_replace('/\s+/u',' ', $t);
  return trim($t);
}
function first_h1($blocks){
  foreach ($blocks as $i=>$b){
    if (($b['type']??'')==='h1'){
      $html = (string)($b['content'] ?? '');
      $text = norm_text($html);
      if ($text !== '') return [$i,$html,$text];
    }
  }
  return [null,'',''];
}
function first_img($blocks){
  foreach ($blocks as $i=>$b){
    if (($b['type']??'')==='img'){
      $src = trim((string)($b['src'] ?? ''));
      if ($src !== '') return [$i,$src];
    }
  }
  return [null,''];
}
function file_key(string $url): string {
  $url = trim($url); if ($url==='') return '';
  $path = parse_url($url, PHP_URL_PATH) ?? $url;
  $base = strtolower(urldecode(basename($path)));
  $dot = strrpos($base, '.'); if ($dot===false) return $base;
  $name = substr($base,0,$dot); $ext = substr($base,$dot+1);
  $name = preg_replace('/-(\d{2,5})x(\d{2,5})$/','',$name);
  $name = preg_replace('/-scaled$/','',$name);
  return $name.'.'.$ext;
}

/* 1) Título de página */
list($h1_idx, $h1_html, $h1_text) = first_h1($blocks);
$page_title_text = $h1_text ?: norm_text($N['titulo'] ?: 'Sin título');

/* 2) HERO */
$hero_src = trim((string)$N['portada_url']);
if ($hero_src===''){
  list($img_idx, $img_src) = first_img($blocks);
  if ($img_src!=='') $hero_src = $img_src;
}
$hero_key = file_key($hero_src);
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= s($page_title_text) ?></title>

<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<link rel="icon" href="img/favicon.png" type="image/png">

<style>
  :root{--bd:#e9eef3;--mut:#5b6672;--ink:#0f1a24;--navy:#15324c;--link:#1f72b6}
  *{box-sizing:border-box}
  html,body{margin:0;padding:0;background:#fff;color:var(--ink);font-family:Poppins,system-ui,Segoe UI,Roboto,Arial,sans-serif}

  body{min-height:100vh;display:flex;flex-direction:column;overflow-x:hidden}
  main{flex:1 0 auto}
  footer{margin-top:0 !important;flex-shrink:0}

  a{color:inherit;text-decoration:none}
  .container{max-width:1100px;margin:0 auto;padding:0 20px}

  .navbar{position:sticky;top:0;z-index:50;background:#fff;border-bottom:1px solid rgba(0,0,0,.06)}
  .navbar .inner{display:flex;align-items:center;justify-content:space-between;height:72px;gap:16px}
  .brand{display:flex;align-items:center;gap:14px;font-weight:800;letter-spacing:.08em}
  .brand .title{line-height:1}
  .brand small{display:block;font-weight:600;opacity:.8;letter-spacing:.2em;margin-top:2px}
  .nav-links{display:flex;align-items:center;gap:22px;font-weight:600}
  .nav-links a{padding:10px 12px;border-radius:8px;transition:background .2s}
  .nav-links a:hover{background:rgba(0,0,0,.05)}
  .nav-links a.active{background:#1f72b6;color:#fff}
  .social{display:flex;align-items:center;gap:14px}
  .datebar{background:var(--navy);color:#fff;font-weight:600}
  .datebar .inner{height:40px;display:flex;align-items:center}

  .note-wrap{max-width:900px;margin:26px auto 44px}
  .nt-title{font-size:clamp(26px,3.2vw,38px);line-height:1.2;font-weight:800;margin:0 0 14px}
  .hero{border-radius:16px;overflow:hidden;border:1px solid var(--bd);margin:0 0 18px}
  .hero img{width:100%;display:block;object-fit:cover;aspect-ratio:16/9}
  .note-body{font-size:clamp(16px,1.2vw,18px);line-height:1.7}
  .note-body h2{font-size:clamp(20px,2.2vw,28px);line-height:1.25;margin:1.25rem 0 .5rem;font-weight:800}
  .note-body p{margin:.9rem 0}
  .note-body .figure{margin:1rem 0;border:1px solid var(--bd);border-radius:12px;overflow:hidden}
  .note-body .figure img{width:100%;display:block}
  .note-body .figcap{font-size:.9rem;color:var(--mut);padding:8px 12px;background:#f7f9fc}
  .note-body .embed{margin:1rem 0}
  .note-body .link{margin:.6rem 0}
  .note-body .quote{font-style:italic;padding:10px 14px;border-left:4px solid #aac3e1;background:#f5f9ff;border-radius:8px}
  .note-body *{max-width:100%}
  .note-body img, .note-body iframe, .note-body video{max-width:100%;height:auto}

  .comments-section{margin:40px 0 10px;padding-top:25px;border-top:1px solid var(--bd);}
  .comments-section h2{font-size:22px;margin:0 0 .3rem;font-weight:700;}
  .comments-intro{font-size:13px;color:var(--mut);margin-bottom:1rem;}
  .comment-form label{display:block;font-weight:600;margin:12px 0 4px;font-size:14px;}
  .comment-form textarea,
  .comment-form input[type="text"],
  .comment-form input[type="email"],
  .comment-form input[type="url"]{
    width:100%;
    border:1px solid #ccc;
    border-radius:2px;
    padding:8px 10px;
    font-family:inherit;
    font-size:14px;
  }
  .comment-form textarea{min-height:150px;resize:vertical;}
  .comment-form .remember{margin-top:10px;font-size:12px;color:var(--mut);}
  .comment-form .remember input{margin-right:5px;}
  .comment-form .btn-submit{
    margin-top:14px;
    border-radius:3px;
    border:1px solid #c2185b;
    background:#fff;
    color:#c2185b;
    padding:8px 16px;
    font-weight:600;
    font-size:14px;
    cursor:pointer;
  }
  .comment-form .btn-submit:hover{
    background:#c2185b;
    color:#fff;
  }
  .comment-alert{margin:20px 0;padding:10px 12px;border-radius:6px;font-size:14px;}
  .comment-alert.ok{background:#e6f4ea;color:#196127;}
  .comment-alert.error{background:#fdecea;color:#b3261e;}
  .comments-list{margin:25px 0 5px;}
  .comments-list h3{font-size:18px;margin:0 0 10px;}
  .comment-item{border-bottom:1px solid #e0e0e0;padding:10px 0;}
  .comment-meta{font-size:13px;color:var(--mut);margin-bottom:4px;}
  .comment-text{font-size:14px;white-space:pre-wrap;}

  footer{background:var(--navy);color:#fff}
  .footer-top{padding:34px 0;border-bottom:1px solid rgba(255,255,255,.08)}
  .footer-grid{display:grid;grid-template-columns:1fr auto;gap:24px;align-items:center}
  .footer-nav{display:flex;flex-wrap:wrap;gap:18px;opacity:.95}
  .footer-nav a{color:#fff;opacity:.9}
  .footer-nav a:hover{opacity:1;text-decoration:underline}
  .footer-brand{font-weight:800;letter-spacing:.12em;opacity:.95}
  .footer-bottom{padding:22px 0;display:flex;justify-content:space-between;align-items:center;gap:20px}
  .footer-social{display:flex;gap:16px}

  .burger{display:none;font-size:28px;border:none;background:transparent}
  @media (max-width:980px){
    .nav-links{display:none;position:absolute;top:72px;left:0;right:0;background:#fff;border-bottom:1px solid rgba(0,0,0,.06);padding:10px 20px;flex-wrap:wrap}
    .nav-links.open{display:flex}
    .burger{display:block}
    .social{display:none}
    .footer-grid{grid-template-columns:1fr}
    .footer-bottom{flex-direction:column;align-items:flex-start}
  }
</style>
</head>
<body>

<header class="navbar">
  <div class="container inner">
    <div class="brand">
      <div class="title">
        <div>FEDERACIÓN DE</div>
        <small>TRANSPORTADORES ARGENTINOS</small>
      </div>
    </div>

    <button class="burger" id="burger" aria-label="Abrir menú"><i class="bi bi-list"></i></button>

    <nav class="nav-links" id="nav">
      <a href="index.php">INICIO</a>
      <a href="notas.php" class="active">NOTAS</a>
      <a href="servicios.php">SERVICIOS</a>
      <a href="delegaciones.php">DELEGACIONES</a>
      <a href="tarifas.php">TARIFAS</a>
      <a href="contacto.php">CONTACTO</a>
    </nav>

    <div class="social">
      <a href="https://www.facebook.com/share/19aQ41jjxB/" target="_blank" rel="noopener" aria-label="Facebook"><i class="bi bi-facebook"></i></a>
      <a href="https://x.com/afetra05?t=ZdX3j9XIGd2PvFizJYMcdg&s=09" target="_blank" rel="noopener" aria-label="X (Twitter)"><i class="bi bi-twitter-x"></i></a>
      <a href="https://www.instagram.com/fe_tr.a?igsh=ZHpqeHB2OW1iNmRq" target="_blank" rel="noopener" aria-label="Instagram"><i class="bi bi-instagram"></i></a>
      <a href="https://www.linkedin.com/in/federaci%C3%B3n-de-transportadores-argentinos-arg-8a33a1327?utm_source=share&utm_campaign=share_via&utm_content=profile&utm_medium=android_app" target="_blank" rel="noopener" aria-label="LinkedIn"><i class="bi bi-linkedin"></i></a>
    </div>
  </div>
</header>

<div class="datebar">
  <div class="container inner"><span id="fecha-hoy">—</span></div>
</div>

<main>
  <div class="container note-wrap">
    <h1 class="nt-title"><?= s($page_title_text) ?></h1>

    <?php if($hero_src): ?>
      <div class="hero"><img src="<?= s($hero_src) ?>" alt="<?= s($page_title_text) ?>"></div>
    <?php endif; ?>

    <div class="note-body">
    <?php
      foreach($blocks as $idx=>$b){
        if (!is_array($b)) continue;
        $type   = $b['type'] ?? '';
        $contentHtml = $b['content'] ?? ($b['text'] ?? '');

        if ($type==='h1' && $idx === $h1_idx) continue;

        if ($type==='img'){
          $src = trim((string)($b['src'] ?? ''));
          if ($src!=='' && $hero_key!=='' && file_key($src) === $hero_key) continue;
        }

        if ($type==='h1'){
          echo '<h2>'. $contentHtml .'</h2>';
        }
        elseif ($type==='h2'){
          echo '<h2>'. $contentHtml .'</h2>';
        }
        elseif ($type==='p'){
          echo '<p>'. $contentHtml .'</p>';
        }
        elseif ($type==='link'){
          $href = trim((string)($b['href'] ?? ''));
          if ($href!==''){
            $label = norm_text($contentHtml) ?: $href;
            echo '<p class="link"><a href="'.s($href).'" target="_blank" rel="noopener">'.s($label).'</a></p>';
          }
        }
        elseif ($type==='quote'){
          echo '<div class="quote">'. $contentHtml .'</div>';
        }
        elseif ($type==='img'){
          $src = trim((string)($b['src'] ?? ''));
          if ($src){
            echo '<figure class="figure"><img src="'.s($src).'" alt="">';
            if (!empty($b['caption'])) echo '<figcaption class="figcap">'.s($b['caption']).'</figcaption>';
            echo '</figure>';
          }
        }
        elseif ($type==='embed'){
          echo '<div class="embed">'. ($b['embedHtml'] ?? '') .'</div>';
        }
      }
    ?>
    </div>

    <?php if($comentario_ok): ?>
      <div class="comment-alert ok">¡Gracias! Tu comentario fue enviado y está pendiente de aprobación.</div>
    <?php endif; ?>

    <?php if($comentario_err): ?>
      <div class="comment-alert error">
        <?php foreach($comentario_err as $e): ?>
          <div><?= s($e) ?></div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <?php if($comentarios): ?>
      <section class="comments-list">
        <h3><?= count($comentarios) ?> comentario<?= count($comentarios) !== 1 ? 's' : '' ?></h3>
        <?php foreach($comentarios as $c): ?>
          <article class="comment-item">
            <div class="comment-meta">
              <strong><?= s($c['nombre']) ?></strong>
              <?php if(!empty($c['created_at'])): ?>
                — <?= date('d/m/Y H:i', strtotime($c['created_at'])) ?>
              <?php endif; ?>
            </div>
            <div class="comment-text"><?= nl2br(s($c['comentario'])) ?></div>
          </article>
        <?php endforeach; ?>
      </section>
    <?php endif; ?>

    <section class="comments-section" id="comentarios">
      <h2>Deja un comentario</h2>
      <p class="comments-intro">Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *</p>

      <form method="post" class="comment-form">
        <label for="comentario">Comentario *</label>
        <textarea id="comentario" name="comentario" required><?= s($old['comentario']) ?></textarea>

        <label for="nombre">Nombre *</label>
        <input type="text" id="nombre" name="nombre" required value="<?= s($old['nombre']) ?>">

        <label for="email">Correo electrónico *</label>
        <input type="email" id="email" name="email" required value="<?= s($old['email']) ?>">

        <label for="web">Web</label>
        <input type="url" id="web" name="web" value="<?= s($old['web']) ?>">

        <div class="remember">
          <label>
            <input type="checkbox" disabled>
            Guardar mi nombre, correo electrónico y sitio web en este navegador para la próxima vez que haga un comentario.
          </label>
        </div>

        <button type="submit" class="btn-submit">Publicar comentario</button>
      </form>
    </section>

  </div>
</main>

<footer>
  <div class="footer-top">
    <div class="container footer-grid">
      <div class="footer-brand">FEDERACIÓN DE TRANSPORTADORES ARGENTINOS</div>
      <nav class="footer-nav" aria-label="Footer">
        <a href="index.php">Inicio</a>
        <a href="notas.php">Notas</a>
        <a href="servicios.php">Servicios</a>
        <a href="delegaciones.php">Delegaciones</a>
        <a href="tarifas.php">Tarifas</a>
        <a href="contacto.php">Contacto</a>
      </nav>
    </div>
  </div>
  <div class="container footer-bottom">
    <div>© <?= date('Y') ?> Fe.Tr.A — Todos los derechos reservados</div>
    <div class="footer-social">
      <a href="https://www.facebook.com/share/19aQ41jjxB/" target="_blank" rel="noopener" aria-label="Facebook"><i class="bi bi-facebook"></i></a>
      <a href="https://x.com/afetra05?t=ZdX3j9XIGd2PvFizJYMcdg&s=09" target="_blank" rel="noopener" aria-label="X (Twitter)"><i class="bi bi-twitter-x"></i></a>
      <a href="https://www.instagram.com/fe_tr.a?igsh=ZHpqeHB2OW1iNmRq" target="_blank" rel="noopener" aria-label="Instagram"><i class="bi bi-instagram"></i></a>
      <a href="https://www.linkedin.com/in/federaci%C3%B3n-de-transportadores-argentinos-arg-8a33a1327?utm_source=share&utm_campaign=share_via&utm_content=profile&utm_medium=android_app" target="_blank" rel="noopener" aria-label="LinkedIn"><i class="bi bi-linkedin"></i></a>
    </div>
  </div>
</footer>
<script>
(function () {
  const el = document.getElementById('fecha-hoy');
  if (!el) return;
  try {
    const d = new Date();
    const fmt = new Intl.DateTimeFormat('es-AR', {
      weekday: 'long',
      day: '2-digit',
      month: 'long'
    });
    let s = fmt.format(d);
    s = s.charAt(0).toUpperCase() + s.slice(1);
    el.textContent = s;
  } catch (e) {
    el.textContent = 'Hoy';
  }
})();

document.getElementById('burger')?.addEventListener('click', function(){
  const nav = document.getElementById('nav');
  if(!nav) return;
  nav.classList.toggle('open');
});
</script>
</body>
</html>
