<?php
/* publicidad_layer.php — Capa para imprimir bloques en las páginas
   USO:
     require_once __DIR__.'/db.php';
     require_once __DIR__.'/publicidad_layer.php';
     // más cerca del cierre de </body>:
     publicidad_layer(pdo(), 'index'); // o 'contacto','tarifas','notas',...
*/
function publicidad_layer(PDO $pdo, string $page_slug): void {
  try{
    $st=$pdo->prepare("SELECT id,page,type,title,media_url,link_url,html,x_pct,y_pct,w_pct,h_pct,zindex
                       FROM publicidad WHERE page=? AND is_enabled=1 ORDER BY zindex, id");
    $st->execute([$page_slug]);
    $rows=$st->fetchAll(PDO::FETCH_ASSOC);
  }catch(Throwable $e){ return; }

  if (!$rows) { echo "<!-- PUB: 0 items ($page_slug) -->"; return; }

  echo '<!-- PUB LAYER start -->';
  echo '<div class="pub-layer" style="position:fixed;inset:0;z-index:2147483647;pointer-events:none;">';

  foreach($rows as $r){
    $x=(float)$r['x_pct']; $y=(float)$r['y_pct']; $w=(float)$r['w_pct']; $h=$r['h_pct']; $z=(int)$r['zindex'];
    echo '<div style="position:absolute;left:'.$x.'%;top:'.$y.'%;width:'.$w.'%;'
        .($h!==null && $h!=='' ? 'height:'.$h.'%;' : '')
        .'z-index:'.$z.';pointer-events:auto;">';

    $type=$r['type'];
    if ($type==='section'){
      echo '<div style="position:absolute;inset:0;background:#15324c;color:#fff;display:flex;align-items:center;justify-content:flex-start;padding:12px 16px;font-weight:700;border-radius:8px">';
      echo htmlspecialchars($r['title'] ?: 'Sección', ENT_QUOTES, 'UTF-8');
      echo '</div>';

    } elseif ($type==='banner'){
      if (!empty($r['media_url'])){
        $src=htmlspecialchars($r['media_url'], ENT_QUOTES, 'UTF-8');
        echo '<img src="'.$src.'" alt="" style="width:100%;height:100%;object-fit:contain;display:block">';
      }

    } elseif ($type==='video'){
      $mu=(string)($r['media_url'] ?? '');
      if (preg_match('~youtu\\.?be~',$mu) && preg_match('~(?:v=|\\.be/)([\\w-]+)~',$mu,$m) && !empty($m[1])){
        echo '<iframe src="https://www.youtube.com/embed/'.$m[1].'" allow="autoplay;encrypted-media" allowfullscreen style="width:100%;height:100%;border:0"></iframe>';
      } elseif ($mu){
        $src=htmlspecialchars($mu, ENT_QUOTES, 'UTF-8');
        echo '<video src="'.$src.'" controls style="width:100%;height:100%;object-fit:cover"></video>';
      }

    } elseif ($type==='html'){
      echo $r['html'];

    } elseif ($type==='link'){
      $label = htmlspecialchars($r['title'] ?: ($r['link_url'] ?: 'Link'), ENT_QUOTES, 'UTF-8');
      $href  = htmlspecialchars($r['link_url'] ?: '#', ENT_QUOTES, 'UTF-8');
      echo '<a href="'.$href.'" target="_blank" style="position:absolute;inset:8px;display:flex;align-items:center;justify-content:center;border:2px dashed #1f72b6;border-radius:8px;text-decoration:none;color:#1f72b6;font-weight:600;background:#fff">'.$label.'</a>';
    }

    echo '</div>';
  }

  echo '</div>';
  echo '<!-- PUB LAYER end -->';
}
