<?php
function lp_now() { return new DateTime('now'); }

function lp_schedule_active(mysqli $conn, int $landing_id): bool {
  // activa si NO hay schedule o si hay una ventana vigente
  $now = lp_now()->format('Y-m-d H:i:s');
  $st = $conn->prepare("SELECT 1 FROM landing_schedule
                        WHERE landing_id=? AND (start_at IS NULL OR start_at<=?) AND (end_at IS NULL OR end_at>=?)
                        LIMIT 1");
  $st->bind_param('iss', $landing_id, $now, $now);
  $st->execute(); $st->store_result();
  return $st->num_rows > 0 || $conn->query("SELECT COUNT(*) c FROM landing_schedule WHERE landing_id={$landing_id}")->fetch_assoc()['c'] == 0;
}

function lp_pick_variant(mysqli $conn, int $landing_id): ?array {
  // cookie stickiness
  $cookieName = "lpv_".$landing_id;
  if (!empty($_COOKIE[$cookieName])) {
    $vid = (int)$_COOKIE[$cookieName];
    $st = $conn->prepare("SELECT id, nombre, peso, estado, hero_image, contenido_html, css_inline, js_inline
                          FROM landing_variants WHERE id=? AND landing_id=? AND estado='activo' LIMIT 1");
    $st->bind_param('ii', $vid, $landing_id);
    $st->execute();
    $res = $st->get_result()->fetch_assoc();
    if ($res) return $res;
  }

  // carga variantes activas
  $st = $conn->prepare("SELECT id, nombre, peso, estado, hero_image, contenido_html, css_inline, js_inline
                        FROM landing_variants WHERE landing_id=? AND estado='activo'");
  $st->bind_param('i', $landing_id);
  $st->execute();
  $r = $st->get_result();
  $vars = []; $total = 0.0;
  while ($row = $r->fetch_assoc()) {
    $w = max(0.0, (float)$row['peso']);
    $row['_w'] = $w;
    $vars[] = $row;
    $total += $w;
  }
  if (!$vars || $total <= 0) return null;

  // ruleta ponderada
  $rnd = mt_rand() / mt_getrandmax() * $total;
  $acc = 0.0;
  foreach ($vars as $v) {
    $acc += $v['_w'];
    if ($rnd <= $acc) {
      // cookie 7 días
      setcookie($cookieName, (string)$v['id'], time()+7*86400, "/");
      return $v;
    }
  }
  return $vars[0];
}

function lp_load_blocks(mysqli $conn, int $landing_id): array {
  // bloques por zonas (main/header/footer, etc.)
  $sql = "SELECT lb.id, lb.nombre, lb.tipo, lb.contenido, lpb.zona, lpb.posicion
          FROM landing_page_blocks lpb
          JOIN landing_blocks lb ON lb.id=lpb.block_id
          WHERE lpb.landing_id=?
          ORDER BY lpb.zona, lpb.posicion ASC";
  $st=$conn->prepare($sql);
  $st->bind_param('i',$landing_id);
  $st->execute();
  $res=$st->get_result();
  $out=[];
  while($row=$res->fetch_assoc()){
    $out[$row['zona']][]=$row; // agrupa por zona
  }
  return $out;
}
