<?php
session_start();
require_once __DIR__ . '/admin/db.php';

function post_json($url, array $payload, $secret=null){
  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => array_filter([
      'Content-Type: application/json',
      $secret ? 'Authorization: Bearer '.$secret : null
    ]),
    CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
    CURLOPT_TIMEOUT => 8
  ]);
  $res = curl_exec($ch);
  $err = curl_error($ch);
  curl_close($ch);
  return $err ?: $res;
}

function safe_redirect(string $url, int $status = 303){
  $url = str_replace(["\r","\n"], '', $url);
  header("Location: ".$url, true, $status);
  exit;
}

function is_abs_url(string $url): bool {
  return (bool) filter_var($url, FILTER_VALIDATE_URL);
}

function is_rel_path(string $url): bool {
  // /ruta o ruta (sin esquema)
  return preg_match('#^/[^/]|^[^:]+$#', $url) === 1;
}

if($_SERVER['REQUEST_METHOD']==='POST'){
  $landing_id = (int)($_POST['landing_id'] ?? 0);
  $variant_id = (int)($_POST['variant_id'] ?? 0);
  $nombre  = trim($_POST['nombre'] ?? '');
  $email   = trim($_POST['email'] ?? '');
  $telefono= trim($_POST['telefono'] ?? '');
  $mensaje = trim($_POST['mensaje'] ?? '');
  $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? ($_SERVER['REMOTE_ADDR'] ?? null);
  $ua = $_SERVER['HTTP_USER_AGENT'] ?? null;

  if($landing_id>0){
    // 1) Guardar lead local
    $st=$conn->prepare("INSERT INTO landing_forms (landing_id,nombre,email,telefono,mensaje,ip_address,user_agent) VALUES (?,?,?,?,?,?,?)");
    $st->bind_param('issssss',$landing_id,$nombre,$email,$telefono,$mensaje,$ip,$ua);
    $st->execute();

    // 2) Track conversión para la variante elegida
    $evt='conversion';
    $sess = session_id() ?: null;
    $vid = $variant_id > 0 ? $variant_id : null;
    $st2 = $conn->prepare("INSERT INTO landing_variant_stats (landing_id, variant_id, event_type, session_id, ip_address, user_agent) VALUES (?,?,?,?,?,?)");
    $st2->bind_param('iissss',$landing_id,$vid,$evt,$sess,$ip,$ua);
    $st2->execute();

    // 3) Enviar a CRMs configurados
    $hooks = $conn->query("SELECT endpoint, method, secret FROM landing_crm_hooks WHERE landing_id={$landing_id} AND active=1")->fetch_all(MYSQLI_ASSOC);
    if($hooks){
      $payload = [
        'landing_id'=>$landing_id,
        'variant_id'=>$vid,
        'lead'=>[
          'nombre'=>$nombre,'email'=>$email,'telefono'=>$telefono,'mensaje'=>$mensaje,
          'ip'=>$ip,'user_agent'=>$ua,'created_at'=>date('c')
        ],
        'utm'=>[
          'source'=>$_POST['utm_source']??null,
          'medium'=>$_POST['utm_medium']??null,
          'campaign'=>$_POST['utm_campaign']??null
        ]
      ];
      foreach($hooks as $h){
        if (strtoupper($h['method'])==='POST') {
          post_json($h['endpoint'], $payload, $h['secret'] ?? null);
        } else {
          @file_get_contents($h['endpoint']);
        }
      }
    }

    // 4) Redirigir al juego (game_url) si existe; si no, fallback a gracias.html
    try {
      $st3 = $conn->prepare("SELECT game_url FROM landing_pages WHERE id=? LIMIT 1");
      $st3->bind_param('i', $landing_id);
      $st3->execute();
      $res = $st3->get_result()->fetch_assoc();
      $game_url = trim((string)($res['game_url'] ?? ''));

      if ($game_url !== '') {
        if (is_abs_url($game_url)) {
          safe_redirect($game_url, 303);
        } elseif (is_rel_path($game_url)) {
          // Normaliza si deseas forzar slash inicial:
          // $game_url = '/' . ltrim($game_url, '/');
          safe_redirect($game_url, 303);
        }
      }
    } catch (Throwable $e) {
      // Si hay error, continua a fallback
    }

    // Fallback
    safe_redirect('gracias.html', 303);
  }
}

http_response_code(400);
echo "Solicitud inválida.";
