<?php
// ruleta/admin/landing_forms_export.php
session_start();
require_once __DIR__ . '/db.php';
if (empty($_SESSION['admin_id'])) { http_response_code(403); echo 'auth'; exit; }

$landing_id = (int)($_GET['landing_id'] ?? 0);
$from = trim($_GET['from'] ?? '');
$to   = trim($_GET['to'] ?? '');

if ($landing_id <= 0) { http_response_code(400); echo 'landing_id requerido'; exit; }

$where = "WHERE lf.landing_id={$landing_id}";
$params = []; $types = '';
if ($from !== '') { $where .= " AND lf.created_at >= ?"; $params[] = $from.' 00:00:00'; $types.='s'; }
if ($to   !== '') { $where .= " AND lf.created_at <= ?"; $params[] = $to  .' 23:59:59'; $types.='s'; }

$sql = "SELECT lf.id, lf.created_at, lp.titulo AS landing, lf.nombre, lf.email, lf.telefono, lf.mensaje, lf.ip_address
        FROM landing_forms lf
        JOIN landing_pages lp ON lp.id=lf.landing_id
        {$where}
        ORDER BY lf.id DESC";

$st = $conn->prepare($sql);
if (!empty($params)) { $st->bind_param($types, ...$params); }
$st->execute();
$res = $st->get_result();

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="landing_'.$landing_id.'_leads.csv"');

$out = fopen('php://output', 'w');
fputcsv($out, ['ID','Fecha','Landing','Nombre','Email','Telefono','Mensaje','IP']);
while($row = $res->fetch_assoc()){
  fputcsv($out, [
    $row['id'],
    $row['created_at'],
    $row['landing'],
    $row['nombre'],
    $row['email'],
    $row['telefono'],
    preg_replace("/\r|\n/"," ", (string)$row['mensaje']),
    $row['ip_address'],
  ]);
}
fclose($out);
