<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../index.php?erreur=4');
    exit;
}

// Basic required fields
$nom = isset($_POST['nom']) ? trim($_POST['nom']) : '';
$prenom = isset($_POST['prenom']) ? trim($_POST['prenom']) : '';
$telephone = isset($_POST['telephone']) ? trim($_POST['telephone']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$ville = isset($_POST['ville']) ? trim($_POST['ville']) : '';
$site = isset($_POST['site']) ? trim($_POST['site']) : '';
$landing_page = isset($_POST['landing_page']) ? trim($_POST['landing_page']) : '';

if ($nom === '' || $prenom === '' || $telephone === '') {
    header('Location: ../index.php?erreur=3');
    exit;
}

// Optional but useful sanitization
$email = filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : '';
$telephone = preg_replace('/[^0-9+]/', '', $telephone);
$landing_page = $landing_page !== '' ? $landing_page : 'offre-speciale-uir';

// UTM params (optional)
$utm_source = isset($_POST['utm_source']) ? trim($_POST['utm_source']) : '';
$utm_campaign = isset($_POST['utm_campaign']) ? trim($_POST['utm_campaign']) : '';
$utm_medium = isset($_POST['utm_medium']) ? trim($_POST['utm_medium']) : '';
$utm_content = isset($_POST['utm_content']) ? trim($_POST['utm_content']) : '';
$utm_term = isset($_POST['utm_term']) ? trim($_POST['utm_term']) : '';

// DB credentials
$servername = 'localhost:3306';
$username = 'offrsqwm_sonarges';
$password = '@Sonarges@123';
$dbname = 'offrsqwm_sonarges';

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    header('Location: ../index.php?erreur=1');
    exit;
}

$stmt = $conn->prepare(
    'INSERT INTO leads_lp (nom, prenom, telephone, email, ville, site, landing_page, utm_source, utm_campaign, utm_medium, utm_content, utm_term, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())'
);

if (!$stmt) {
    header('Location: ../index.php?erreur=1');
    exit;
}

$stmt->bind_param(
    'ssssssssssss',
    $nom,
    $prenom,
    $telephone,
    $email,
    $ville,
    $site,
    $landing_page,
    $utm_source,
    $utm_campaign,
    $utm_medium,
    $utm_content,
    $utm_term
);

if ($stmt->execute()) {
    $stmt->close();
    $conn->close();
    header('Location: ../thankyou.html');
    exit;
}

$stmt->close();
$conn->close();
header('Location: ../index.php?erreur=2');
exit;
?>
