<?php
/* ads_render.php — renderizado de bloques por página+slot
   Uso:
     require_once __DIR__.'/db.php';
     require_once __DIR__.'/ads_render.php';
     render_ads(pdo(), 'index', 'hero');
*/
function render_ads(PDO $pdo, string $page_slug, string $slot){
  try{
    $st=$pdo->prepare("SELECT id,type,title,body_html,image_url,video_url,link_url,styles_json
                       FROM ad_blocks
                       WHERE page_slug=? AND slot=? AND is_active=1
                       ORDER BY sort_order ASC, id ASC");
    $st->execute([$page_slug,$slot]);
    $rows=$st->fetchAll(PDO::FETCH_ASSOC);
  }catch(Throwable $e){ echo "<!-- ads_render error: ".htmlspecialchars($e->getMessage())." -->"; return; }

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

  foreach($rows as $r){
    $cls=''; $style='';
    if(!empty($r['styles_json'])){
      $j=json_decode($r['styles_json'], true);
      if(is_array($j)){
        if(!empty($j['class'])) $cls.=' '.$j['class'];
        if(!empty($j['style'])) $style.=$j['style'];
      }
    }
    echo '<div class="ad-block'.htmlspecialchars($cls).'"'.
         ($style!==''? ' style="'.htmlspecialchars($style,ENT_QUOTES,'UTF-8').'"':'').'>';

    $type=$r['type']; $title=$r['title'];
    if($type==='html'){
      echo $r['body_html'] ?? '';

    } elseif($type==='image'){
      $src=trim((string)$r['image_url']);
      if($src!==''){
        $img='<img src="'.htmlspecialchars($src,ENT_QUOTES,'UTF-8').'" alt="'.htmlspecialchars($title??'',ENT_QUOTES,'UTF-8').'" style="max-width:100%;height:auto;display:block">';
        if(!empty($r['link_url'])){
          $href=htmlspecialchars($r['link_url'],ENT_QUOTES,'UTF-8');
          echo '<a href="'.$href.'" target="_blank" rel="noopener">'.$img.'</a>';
        } else {
          echo $img;
        }
      }

    } elseif($type==='video'){
      $vu=trim((string)$r['video_url']);
      if($vu!==''){
        if(preg_match('~youtu\\.?be~',$vu) && preg_match('~(?:v=|\\.be/)([\\w-]+)~',$vu,$m) && !empty($m[1])){
          echo '<div class="ad-video" style="position:relative;padding-top:56.25%"><iframe src="https://www.youtube.com/embed/'.$m[1].'" allow="autoplay;encrypted-media" allowfullscreen style="position:absolute;inset:0;width:100%;height:100%;border:0"></iframe></div>';
        } else {
          $src=htmlspecialchars($vu,ENT_QUOTES,'UTF-8');
          echo '<video src="'.$src.'" controls style="width:100%;height:auto;display:block"></video>';
        }
      }

    } elseif($type==='link'){
      $label=htmlspecialchars($title?:($r['link_url']?:'Ver más'),ENT_QUOTES,'UTF-8');
      $href =htmlspecialchars($r['link_url']?:'#',ENT_QUOTES,'UTF-8');
      echo '<a class="ad-link" href="'.$href.'" target="_blank" rel="noopener" style="display:inline-flex;align-items:center;gap:8px;text-decoration:none;font-weight:600">'.$label.'</a>';

    } elseif($type==='section'){
      // Contenedor con título + HTML/imagen opcional
      echo '<section class="ad-section" style="padding:16px;border-radius:12px;background:#15324c;color:#fff">';
      if($title) echo '<h3 style="margin:0 0 8px">'.htmlspecialchars($title,ENT_QUOTES,'UTF-8').'</h3>';
      if(!empty($r['body_html'])) echo '<div>'.$r['body_html'].'</div>';
      if(!empty($r['image_url'])){
        echo '<img src="'.htmlspecialchars($r['image_url'],ENT_QUOTES,'UTF-8').'" alt="" style="max-width:100%;height:auto;display:block;margin-top:8px">';
      }
      echo '</section>';
    }

    echo '</div>';
  }
}
