<?php
// secciones_embed.php — Renderiza las secciones nuevas
if (!function_exists('pdo')) { require __DIR__.'/db.php'; }
$pdo = pdo();

// Permite forzar la página desde el include: $SECC_PAGE = 'index.php';
$page = null;
if (isset($SECC_PAGE) && $SECC_PAGE) {
  $page = basename($SECC_PAGE);
} elseif (!empty($_GET['page'])) {
  $page = basename($_GET['page']);
} else {
  $page = basename($_SERVER['SCRIPT_NAME'] ?? 'index.php');
}

$stmt = $pdo->prepare("SELECT * FROM secciones WHERE enabled=1 AND page=? ORDER BY orden ASC, id ASC");
$stmt->execute([$page]);
$secciones = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Si no hay secciones, no rompemos el layout y dejamos una marca de depuración opcional
if (!$secciones) {
  if (isset($_GET['debug'])) {
    header('Content-Type: text/html; charset=utf-8');
    echo "<!-- secciones_embed.php: Sin secciones para page='{$page}' -->";
  }
  return;
}

$ids = array_column($secciones, 'id');
$in  = implode(',', array_fill(0, count($ids), '?'));
$items = [];
if ($ids) {
  $qs = $pdo->prepare("SELECT * FROM seccion_items WHERE enabled=1 AND seccion_id IN ($in) ORDER BY z ASC, id ASC");
  $qs->execute($ids);
  while ($r = $qs->fetch(PDO::FETCH_ASSOC)) {
    $r['data'] = json_decode($r['content_json'] ?? '[]', true) ?: [];
    $items[$r['seccion_id']][] = $r;
  }
}

function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
?>
<style>
  .sx-page { position: relative; width: 100%; }
  .sx-sec  { position: relative; width: 100%; box-sizing: border-box; }
  .sx-item { position: absolute; box-sizing: border-box; }
  .sx-title { font-weight: 800; font-size: clamp(22px, 3vw, 42px); line-height: 1.1; }
  .sx-paragraph { font-size: clamp(14px, 1.4vw, 18px); line-height: 1.6; }
</style>

<div class="sx-page">
  <?php foreach ($secciones as $s):
    $sid = (int)$s['id'];
    $h   = (int)($s['h'] ?? 700);
    $pad = (int)($s['padding'] ?? 48);
    $bg  = $s['bg'] ?: '#ffffff';
  ?>
  <section class="sx-sec" id="sx-sec-<?= $sid ?>" style="min-height:<?= $h ?>px; padding:<?= $pad ?>px; background:<?= esc($bg) ?>;">
    <?php if (!empty($items[$sid])): ?>
      <?php foreach ($items[$sid] as $it):
        $left = (int)($it['x'] ?? 0);
        $top  = (int)($it['y'] ?? 0);
        $w    = $it['w'] !== null ? (int)$it['w'] : null;
        $z    = (int)($it['z'] ?? 1);
        $cs   = "left:{$left}px; top:{$top}px; z-index:{$z};";
        if ($w !== null && $w > 0) $cs .= "width:{$w}px;";
        $d    = $it['data'];
        $type = $it['type'];
      ?>
      <div class="sx-item" style="<?= esc($cs) ?>">
        <?php if ($type==='title'): ?>
          <div class="sx-title"><?= esc($d['text'] ?? 'Título') ?></div>

        <?php elseif ($type==='paragraph'): ?>
          <div class="sx-paragraph"><?= nl2br(esc($d['text'] ?? 'Párrafo')) ?></div>

        <?php elseif ($type==='image'):
          $src = $d['src'] ?? ''; $alt = $d['alt'] ?? ''; $maxw = (int)($d['maxw'] ?? 0); ?>
          <img src="<?= esc($src) ?>" alt="<?= esc($alt) ?>" style="display:block;max-width:<?= $maxw>0?$maxw.'px':'100%' ?>;height:auto;" />

        <?php elseif ($type==='html'): ?>
          <div><?= $d['html'] ?? '' ?></div>

        <?php elseif ($type==='link'):
          $url = $d['url'] ?? '#'; $txt = $d['text'] ?? $url; ?>
          <a href="<?= esc($url) ?>"><?= esc($txt) ?></a>

        <?php elseif ($type==='video'):
          $url = $d['url'] ?? ''; ?>
          <video src="<?= esc($url) ?>" controls style="max-width:100%;height:auto;"></video>
        <?php endif; ?>
      </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </section>
  <?php endforeach; ?>
</div>
