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

// Database connection
$host = "localhost";
$user = "celatex_hotmart_usr";
$password = "Y9etWBlFd4P95rkMmEjo";
$dbname = "celatex_hotmart";

$conn = new mysqli($host, $user, $password, $dbname);
if ($conn->connect_error) {
    die("Database connection failed: " . $conn->connect_error);
}

// Get data from POST
$email = $_POST['email'] ?? '';
$source_id = $_POST['id'] ?? 'unknown';

// Validate basic input
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    die("Invalid email format.");
}

// Detect channel folder from URI (e.g. /vida_sana/register.php => vida_sana)
$uri_parts = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
$channel = count($uri_parts) > 1 ? $uri_parts[count($uri_parts) - 2] : 'root';

// Prepare and execute insert
$stmt = $conn->prepare("INSERT INTO subscribers (email, source_id, status, channel) VALUES (?, ?, 1, ?)");
if (!$stmt) {
    die("Prepare failed: " . $conn->error);
}
$stmt->bind_param("sss", $email, $source_id, $channel);
$stmt->execute();
$stmt->close();
$conn->close();

// Redirect to thank you page
header("Location: thanks.html");
exit();
?>
