<?php
ob_start(); // ✅ Start output buffering to prevent premature output

ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

session_start();
require 'db.php'; // Ensure this connects to your database

// ✅ Declare redirect URL early to avoid "undefined variable" issues
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$base_url = "$protocol://" . $_SERVER['HTTP_HOST']; // Get the current domain dynamically
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/');
$redirect_url = $base_url . $path . "/user-dashboard.php";



// Check if 'ref' parameter exists and is not empty
if (!isset($_GET['ref']) || empty(trim($_GET['ref']))) {
    $error = "You must be referred by someone to register. Please contact support for more details.";
}

require_once 'send-email.php';

// Fetch branding details
$share_code = $_GET['code'] ?? null;

if ($share_code) {
    $stmt = $pdo->prepare("SELECT background, color_theme, font_headline, font_subheading FROM lead_capture_pages WHERE share_code = ?");
    $stmt->execute([$share_code]);
    $leadPage = $stmt->fetch(PDO::FETCH_ASSOC);

    $background = 'assets/backgrounds/' . ($leadPage['background'] ?? 'default-bg.jpg');
    $border_color = $leadPage['color_theme'] ?? '#007bff';

    // ✅ Set Default Fonts If Not Defined in DB
    $headlineFont = (!isset($leadPage['font_headline']) || trim($leadPage['font_headline']) === '') ? 'Anton' : $leadPage['font_headline'];
    $subheadingFont = (!isset($leadPage['font_subheading']) || trim($leadPage['font_subheading']) === '') ? 'Pacifico' : $leadPage['font_subheading'];
} else {
    $background = 'default-bg.jpg';
    $border_color = '#007bff'; // Default to blue
}

$referrer_id = $_GET['ref'] ?? null; // Get the referrer ID from URL, default to null

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $submitted_answer = (int) ($_POST['math_answer'] ?? 0);
    $correct_answer = $_SESSION['math_answer'] ?? null;

    if ($submitted_answer !== $correct_answer) {
        $error = "Incorrect math answer. Please try again.";
    } else {
        unset($_SESSION['math_answer']); // Prevent reuse

    $user_id = trim($_POST['user_id']);
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $confirm_password = trim($_POST['confirm_password']);

    if ($password !== $confirm_password) {
        $error = "Passwords do not match!";
    } else {
        // Check if User ID already exists
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE user_id = ? OR email = ?");
        $stmt->execute([$user_id, $email]);
        if ($stmt->fetchColumn() > 0) {
            $error = "User ID or Email already taken!";
        } else {
            // Insert new user
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

            // ✅ Fetch tracking source from leads table BEFORE inserting the user
            $stmt = $pdo->prepare("SELECT source FROM leads WHERE email = ? LIMIT 1");
            $stmt->execute([$email]);
            $tracking_source = $stmt->fetchColumn() ?: null; // If not found, set to NULL

            // ✅ Now insert the user, including tracking_source
            $stmt = $pdo->prepare("INSERT INTO users (user_id, first_name, last_name, email, edit_token, referrer_id, tracking_source) VALUES (?, ?, ?, ?, ?, ?, ?)");
            if ($stmt->execute([$user_id, $first_name, $last_name, $email, $hashedPassword, $referrer_id, $tracking_source])) {
                // ✅ Send Welcome Email AFTER successful registration
                sendWelcomeEmail($email, $first_name);

                // ✅ Send Referral Email IF a referrer exists
                if (!empty($referrer_id)) {
                    // ✅ Get referrer details from the database
                    $stmt = $pdo->prepare("SELECT first_name, email FROM users WHERE user_id = ? LIMIT 1");
                    $stmt->execute([$referrer_id]);
                    $referrer = $stmt->fetch(PDO::FETCH_ASSOC);

                    if ($referrer) {
                        $referrerEmail = $referrer['email'];
                        $referrerName = $referrer['first_name'];

                        // ✅ Now send the referral email
                        sendReferralEmail($referrerEmail, $referrerName, $first_name);
                    }
                }

                // ✅ Auto-login the user after registration
                $_SESSION['logged_in_user'] = $user_id;
                $_SESSION['first_name'] = $first_name;
                $_SESSION['last_name'] = $last_name;
                $_SESSION['email'] = $email;
                session_write_close(); // ✅ Ensure session is saved before redirect

                // ✅ Get referrer LeadsLeap info
                $stmt = $pdo->prepare("SELECT leadsleap_user_id, leadsleap_list_id_referrals FROM users WHERE user_id = ?");
                $stmt->execute([$referrer_id]);
                $referrer = $stmt->fetch(PDO::FETCH_ASSOC);

                $lluid = htmlspecialchars($referrer['leadsleap_user_id'] ?? '');
                $lllid = htmlspecialchars($referrer['leadsleap_list_id_referrals'] ?? '');

                // ✅ Debugging: Print Redirect URL (Only if it is set)
                if (!empty($redirect_url)) {

                    error_log("Redirect URL Debug: " . $redirect_url); // ✅ Log Redirect URL in error_log
                } else {
                    echo "<p style='color: red; font-size: 18px;'>Error: Redirect URL is empty!</p>";
                    error_log("Redirect URL is empty!");
                }
$name_for_leadsleap = trim($first_name . ' ' . $last_name);

                // ✅ Output hidden form to LeadsLeap
                echo <<<HTML
                <form id="leadsleapRedirectForm" method="post" action="https://www.sendsteed.com/subscribe/">
                    <input type="hidden" name="n{$lllid}" value="{$name_for_leadsleap}">
                    <input type="hidden" name="e{$lllid}" value="{$email}">
                    <input type="hidden" name="lllid" value="{$lllid}">
                    <input type="hidden" name="lluid" value="{$lluid}">
                    <input type="hidden" name="redirect" value="{$redirect_url}">
                </form>
                <script>
                    document.getElementById("leadsleapRedirectForm").submit();
                </script>
                HTML;
            } else {
                $error = "Registration failed, please try again!";
            }
        }
    }
}
}
ob_end_flush(); // ✅ End output buffering
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Registration</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    <!-- ✅ Preload Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=<?= urlencode($headlineFont); ?>:wght@400;700&family=<?= urlencode($subheadingFont); ?>:wght@400;700&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
        <style>
        html, body {
            height: 100%;
            margin: 0;
            display: flex;
            flex-direction: column;
            html, body {
    height: 100%;
    margin: 0;
    display: flex;
    flex-direction: column;
    background: url('<?= htmlspecialchars($background); ?>') no-repeat center center fixed;
    background-size: cover;
}

h2 {
    font-size: 2.5rem;
    font-weight: bold;
    font-family: "<?= htmlspecialchars($headlineFont); ?>", sans-serif !important;
    text-shadow: 2px 2px 10px rgba(0, 0, 0, 0.5);
    color: white;
    text-align: center;
}

p {
    font-size: 1.4rem;
    font-family: "<?= htmlspecialchars($subheadingFont); ?>", cursive !important;
    text-shadow: 1px 1px 5px rgba(0, 0, 0, 0.3);
    color: white;
    text-align: center;
}

/* ✅ Ensure All Links are White */
a {
    color: white !important;
    text-decoration: none; /* Optional: Removes underline */
}

a:hover {
    color: rgba(255, 255, 255, 0.8) !important; /* Slight dimming effect on hover */
    text-decoration: underline; /* Optional: Adds an underline on hover */
}


            background-size: cover;
        }

        .content-wrapper {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            width: 100%;
        }

        .logo-container {
            text-align: center;
            margin-bottom: 20px;
        }

        .logo-img {
            max-width: 150px;
        }

.registration-container {
    max-width: 500px;
    width: 90%;
    background: rgba(0, 0, 0, 0.65); /* Dark transparent background */
    padding: 40px;
    border-radius: 15px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4);
    backdrop-filter: blur(5px); /* Smooth blur effect */
    color: white;
}
@media (min-width: 768px) {
    .registration-container {
        max-width: 600px;
    }
}


        .footer {
            background-color: rgba(0, 0, 0, 0.6);
            color: white;
            text-align: center;
            padding: 15px;
            font-size: 14px;
            width: 100%;
            position: relative;
            bottom: 0;
        }
        
.btn-primary {
    background: <?= htmlspecialchars($border_color); ?> !important;
    border: none !important; /* Ensures no border */
    color: <?= ($border_color === 'yellow') ? 'black' : 'white'; ?> !important;
    font-family: "<?= htmlspecialchars($headlineFont); ?>", sans-serif;
    font-size: 23px;
    font-weight: bold;
    text-transform: uppercase;
    padding: 14px;
    border-radius: 6px;
    transition: all 0.3s ease-in-out;
    outline: none !important; /* Prevents outline on focus */
    box-shadow: none !important; /* Removes any default focus glow */
}

/* ✅ Also remove any blue focus border */
.btn-primary:focus, 
.btn-primary:active {
    outline: none !important;
    box-shadow: none !important;
    border: none !important;
}

.btn-primary:hover {
    filter: brightness(1.2);
    transform: translateY(-5px);
    transform: scale(1.05); /* Slightly enlarges */
}

/* ✅ Unified Input Field Styling */
input.form-control {
    background: rgba(255, 255, 255, 0.15); /* Slight transparency */
    border: 2px solid <?= htmlspecialchars($border_color); ?>; /* Uses dynamic color */
    border-radius: 8px; /* Rounded for smooth look */
    padding: 12px;
    font-size: 16px;
    color: white !important;
    font-weight: 500;
    outline: none;
    transition: all 0.3s ease-in-out, transform 0.2s;
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.2); /* Inner shadow for depth */
}

/* ✅ Focus Effect - Adds Glow & Scale */
input.form-control:focus {
    background: rgba(255, 255, 255, 0.25); /* More visible when focused */
    border-color: <?= htmlspecialchars($border_color); ?>;
    box-shadow: 0 0 15px rgba(255, 100, 0, 0.8), inset 0 0 6px rgba(0, 0, 0, 0.3);
    transform: scale(1.02); /* Slight scaling for an interactive feel */
    color: white !important;
}

/* ✅ Label Styling - More Readable */
label {
    font-weight: 600; /* Slightly bolder */
    font-size: 16px;
    color: rgba(255, 255, 255, 0.9); /* Bright white for better contrast */
}


/* ✅ Add focus effect */
input:focus {
    background: rgba(255, 255, 255, 0.3);
    border-color: #ff6a00; /* Slightly lighter red when focused */
    box-shadow: 0 0 8px rgba(255, 77, 0, 0.8);
}

.login-link {
    font-size: 15px;
    font-style: italic;
    color: rgba(255, 255, 255, 0.7);
    transition: color 0.3s ease-in-out;
}

/* ✅ Make it pop when hovered */
.login-link:hover {
    color: #ff6a00;
    text-decoration: underline;
}


/* ✅ Make placeholder text white */
::placeholder {
    color: rgba(255, 255, 255, 0.7); /* White with slight transparency */
    font-style: italic; /* Optional: makes it look elegant */
}

/* ✅ For older browser compatibility */
input::placeholder {
    color: rgba(255, 255, 255, 0.7);
}

input:-ms-input-placeholder { /* Internet Explorer */
    color: rgba(255, 255, 255, 0.7);
}

input::-webkit-input-placeholder { /* Safari, Chrome */
    color: rgba(255, 255, 255, 0.7);
}

input::-moz-placeholder { /* Firefox */
    color: rgba(255, 255, 255, 0.7);
}

input:-moz-placeholder { /* Firefox 4-18 */
    color: rgba(255, 255, 255, 0.7);
}
/* ✅ Force White Placeholders */
input.form-control::placeholder {
    color: rgba(255, 255, 255, 1); /* Fully white */
    opacity: 1 !important; /* Forces full opacity */
    font-style: italic; /* Optional: Adds elegance */
}
/* ✅ White Placeholder Text for All Browsers */
input.form-control::placeholder,
input.form-control:-ms-input-placeholder,  /* Internet Explorer */
input.form-control::-webkit-input-placeholder, /* Chrome, Safari */
input.form-control::-moz-placeholder, /* Firefox */
input.form-control:-moz-placeholder { /* Older Firefox */
    color: rgba(255, 255, 255, 1) !important; /* Fully white */
    opacity: 1 !important;
    font-style: italic;
}


    </style>
</head>
<body>
<?php include 'google-translate-widget-front-end.php'; ?>
    <div class="content-wrapper">
        <?php if (!empty($logo)): ?>
            <div class="logo-container">
                <img src="<?= htmlspecialchars($logo); ?>" alt="Logo" class="logo-img">
            </div>
        <?php endif; ?>

        <div class="registration-container">
        <?php if (!empty($error)): ?>
    <div class="alert alert-danger text-center">
        <?= htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

            <h2><i class="fa fa-user-circle"></i> JOIN NOW – IT’S FREE!</h2>
            <?php if (!empty($error)): ?>
                <p class="error-message"> <?= htmlspecialchars($error); ?> </p>
            <?php endif; ?>
<?php if (empty($error)): ?> 
<form action="user-registration.php?code=<?= htmlspecialchars($_GET['code'] ?? ''); ?>&ref=<?= htmlspecialchars($_GET['ref'] ?? ''); ?>" method="POST">

<?php
    // Generate simple math challenge
    $num1 = rand(1, 10);
    $num2 = rand(1, 10);
    $_SESSION['math_answer'] = $num1 + $num2;
?>

    <div class="mb-3">
        <label for="user_id" class="form-label">Choose Your User ID</label>
        <input type="text" id="user_id" name="user_id" class="form-control" placeholder="Enter a unique username" required>
    </div>
    <div class="mb-3">
        <label for="first_name" class="form-label">First Name</label>
        <input type="text" id="first_name" name="first_name" class="form-control" placeholder="John" required>
    </div>
    <div class="mb-3">
        <label for="last_name" class="form-label">Last Name</label>
        <input type="text" id="last_name" name="last_name" class="form-control" placeholder="Doe" required>
    </div>
    <div class="mb-3">
        <label for="email" class="form-label">Email Address</label>
        <input type="email" id="email" name="email" class="form-control" placeholder="yourname@example.com" required>
    </div>
    <div class="mb-3">
        <label for="password" class="form-label">Password</label>
        <input type="password" id="password" name="password" class="form-control" placeholder="Create a strong password" required>
    </div>
    <div class="mb-3">
        <label for="confirm_password" class="form-label">Confirm Password</label>
        <input type="password" id="confirm_password" name="confirm_password" class="form-control" placeholder="Re-enter your password" required>
    </div>
    
    <div class="mb-3">
    <label for="math_answer" class="form-label">What is <?= $num1 ?> + <?= $num2 ?>?</label>
    <input type="number" id="math_answer" name="math_answer" class="form-control" placeholder="Enter your answer" required>
</div>

    <button type="submit" class="btn btn-primary w-100">CREATE MY FREE ACCOUNT</button>
</form>
<?php endif; ?>
            <p class="mt-3">
                Already have an account? <a href="user-login.php">Login here</a>
            </p>
        </div>
    </div>

<footer class="footer text-center" style="color: white;">
    &copy; <?= str_replace(['https://', 'http://', 'www.'], '', $_SERVER['HTTP_HOST']); ?>, All Rights Reserved.
    <br>
    <span style="color: white; font-size: 13px; display: block; margin-top: 5px;">
        Note: This is a free platform, but inactive accounts are periodically reviewed. If your account remains unsetup and inactive after 14 days, it may be removed without prior notice. Setup is quick and easy, and your sponsor is available to help if needed. 14 days is more than enough to look around and decide. Please ensure your account is active to avoid deletion.
    </span>
</footer>


    


</body>
</html>
