<?php
header('Content-Type: application/json');

// Configuración de la base de datos
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "aviacionpagina";

// Crear conexión
$conn = new mysqli($servername, $username, $password, $dbname);

// Verificar conexión
if ($conn->connect_error) {
    echo json_encode([
        'success' => false,
        'message' => 'Connection failed: ' . $conn->connect_error
    ]);
    exit;
}

// Recoger y validar email
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode([
        'success' => false,
        'message' => 'Por favor ingresa un email válido'
    ]);
    exit;
}

// Verificar si el email ya existe
$check = $conn->prepare("SELECT id FROM suscriptores WHERE email = ?");
$check->bind_param("s", $email);
$check->execute();
$check->store_result();

if ($check->num_rows > 0) {
    echo json_encode([
        'success' => false,
        'message' => 'Este email ya está suscrito'
    ]);
    exit;
}

// Insertar nuevo suscriptor
$stmt = $conn->prepare("INSERT INTO suscriptores (email, fecha_registro, ip) VALUES (?, NOW(), ?)");
$ip = $_SERVER['REMOTE_ADDR'];
$stmt->bind_param("ss", $email, $ip);

if ($stmt->execute()) {
    echo json_encode([
        'success' => true,
        'message' => 'Gracias por suscribirte'
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Error al guardar la suscripción'
    ]);
}

$conn->close();
?>