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

require_once 'db.php';

// ✅ Click Tracking Snippet
$refCode = $_GET['ref'] ?? '';
$shareCode = $_GET['code'] ?? '';
$source = $_GET['source'] ?? '';


// Only track clicks if a referral code is present
if (!empty($refCode)) {
    // Get numeric user_id from ref code
    $stmt = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
    $stmt->execute([$refCode]);
    $userId = $stmt->fetchColumn();

    if ($userId) {
$ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';

// ✅ Free Country Detection using ip-api.com (No key needed, 45 req/min)
$country = '';
$countryCode = '';
$ipData = @json_decode(file_get_contents("http://ip-api.com/json/{$ipAddress}?fields=country,countryCode"));

if (!empty($ipData) && $ipData->country) {
    $country = $ipData->country;
    $countryCode = $ipData->countryCode ?? '';
}


$shareCode = $_GET['code'] ?? '';
$source = $_GET['source'] ?? '';

$stmt = $pdo->prepare("INSERT INTO clicks (user_id, ip_address, user_agent, ref_code, country, country_code, share_code, source) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$userId, $ipAddress, $userAgent, $refCode, $country, $countryCode, $shareCode, $source]);


    }
}


// ✅ Get the Share Code & Referrer from URL
$share_code = $_GET['code'] ?? null;
if (empty($share_code)) {
    die("Error: Share code missing in request.");
}

$referrer = $_GET['ref'] ?? null;

// ✅ Fetch Lead Capture Page Data
if (!$share_code) {
    die("Error: Missing Share Code.");
}

$stmt = $pdo->prepare("SELECT * FROM lead_capture_pages WHERE share_code = ?");
$stmt->execute([$share_code]);
$leadPage = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$leadPage) {
    die("Error: Lead Capture Page Not Found.");
}


// ✅ Fetch Referring User's Details
$stmt = $pdo->prepare("SELECT first_name, last_name, email, leadsleap_user_id, leadsleap_list_id FROM users WHERE user_id = ?");
$stmt->execute([$referrer]);
$referrerData = $stmt->fetch(PDO::FETCH_ASSOC);


// ✅ Fetch Branding Open Graph Image from DB
$brandingStmt = $pdo->query("SELECT open_graph_image FROM branding LIMIT 1");
$brandingData = $brandingStmt->fetch(PDO::FETCH_ASSOC);

// ✅ Generate absolute OG image URL
$rawImage = $brandingData['open_graph_image'] ?? '';
if (!empty($rawImage) && !str_starts_with($rawImage, 'http')) {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    $og_image = $protocol . "://" . $host . "/" . ltrim($rawImage, '/');
} else {
    $og_image = $rawImage ?: 'https://mlmlead.pro/assets/images/generic-preview.jpg';
}

// ✅ Clean fallback for description
$og_description = !empty($leadPage['subheadline']) 
    ? mb_strimwidth(strip_tags($leadPage['subheadline']), 0, 200, '…')
    : "Discover this exciting opportunity!";

// ✅ Full page URL
$dir = rtrim(dirname($_SERVER['REQUEST_URI']), '/');
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $dir;
$og_url = $base_url . '/lead.php?code=' . urlencode($share_code);
if (!empty($referrer)) {
    $og_url .= '&ref=' . urlencode($referrer);
}
if (!empty($_GET['source'])) {
    $og_url .= '&source=' . urlencode($_GET['source']);
}




// ✅ Set LeadsLeap Details (If Available)
$leadsleap_user_id = $referrerData['leadsleap_user_id'] ?? null;
$leadsleap_list_id = $referrerData['leadsleap_list_id'] ?? null;

// ✅ Handle Referrer Branding Gracefully
if ($referrerData) {
    $referrerName = htmlspecialchars($referrerData['first_name'] . ' ' . $referrerData['last_name']);
    $referrerEmail = htmlspecialchars($referrerData['email']);
} else {
    $referrerName = "Anonymous User"; // Default name
    $referrerEmail = "anonymous@example.com"; // Default email
}

// ✅ Generate Gravatar Image
$gravatarHash = md5(strtolower(trim($referrerEmail)));
$gravatarURL = "https://www.gravatar.com/avatar/$gravatarHash?s=100&d=mp";

// ✅ Retrieve user-selected fonts from the database
$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'];

// ✅ Handle CTA Text (icon + label)
$ctaText = $leadPage['cta_text'] ?? '';
if (!empty($ctaText) && strpos($ctaText, ' ') !== false) {
    [$ctaIcon, $ctaLabel] = explode(' ', $ctaText, 2);
} else {
    $ctaIcon = 'fa-arrow-right';
    $ctaLabel = 'YES, LET ME IN!';
}



?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($leadPage['headline']); ?></title>
    

<!-- ✅ Facebook Open Graph Meta Tags -->
<meta property="og:title" content="<?= htmlspecialchars($leadPage['headline']); ?>" />
<meta property="og:description" content="<?= htmlspecialchars($og_description); ?>" />
<meta property="og:image" content="<?= htmlspecialchars($og_image); ?>" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:url" content="<?= htmlspecialchars($og_url); ?>" />
<meta property="og:type" content="website" />

<!-- ✅ Twitter Card Tags -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="<?= htmlspecialchars($leadPage['headline']); ?>" />
<meta name="twitter:description" content="<?= htmlspecialchars($og_description); ?>" />
<meta name="twitter:image" content="<?= htmlspecialchars($og_image); ?>" />
<meta name="twitter:url" content="<?= htmlspecialchars($og_url); ?>" />





    <!-- ✅ Preload Google Fonts BEFORE CSS -->
    <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">

    <!-- ✅ Load Bootstrap AFTER Fonts to Prevent Overrides -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">

    <style>
    /* ✅ Force Google Fonts to Load First */
    * {
        font-family: "<?= htmlspecialchars($headlineFont); ?>", sans-serif !important;
    }

body {
    background: url('assets/backgrounds/<?= htmlspecialchars($leadPage['background']); ?>') no-repeat center center fixed;
    background-size: cover;
    color: white;
    text-align: center;
    padding: 20px;
    display: flex;
    flex-direction: column; /* ✅ Ensures normal document flow */
    align-items: center;
    justify-content: flex-start; /* ✅ Prevents forced stretching */
    min-height: 100vh;
    font-display: swap;
}

    
html, body {
    min-height: 100vh;
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
}


    /* ✅ Ensure Container Uses Correct Font */
.container {
    justify-content: center;
    max-width: 600px;
    background: rgba(0, 0, 0, 0.65);
    padding: 40px;
    border-radius: 15px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4);
    backdrop-filter: blur(5px);
    margin-top: min(8vh, 80px); /* ✅ Ensures spacing adapts to screen size */
}




    /* ✅ Apply User-Selected Fonts */
h1 {
    font-size: clamp(2rem, 5vw, 2.5rem); /* ✅ Responsive font size */
    font-weight: bold;
    font-family: "<?= htmlspecialchars($headlineFont); ?>", sans-serif !important;
    text-shadow: 2px 2px 10px rgba(0, 0, 0, 0.5);
    margin-bottom: 10px; /* ✅ Adds space below the headline */
}


p {
    font-size: clamp(1rem, 4vw, 1.4rem); /* ✅ Responsive subheadline */
    font-family: "<?= htmlspecialchars($subheadingFont); ?>", cursive !important;
    text-shadow: 1px 1px 5px rgba(0, 0, 0, 0.3);
    margin-bottom: 15px; /* ✅ Ensures proper spacing */
}


    /* ✅ Ensure Bootstrap Doesn't Override */
    form input {
        width: 100%;
        padding: 12px;
        margin: 10px 0;
        border: 2px solid <?= htmlspecialchars($leadPage['color_theme']); ?>;
        border-radius: 8px;
        font-size: 18px;
        background: rgba(255, 255, 255, 0.2);
        color: white;
        outline: none;
        transition: all 0.3s ease-in-out;
    }

    form input::placeholder {
        color: rgba(255, 255, 255, 0.7);
    }

    form input:focus {
        background: rgba(255, 255, 255, 0.3);
    }

/* ✅ Privacy Disclaimer */
.privacy-disclaimer {
    font-size: 0.9rem;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.8);
    text-align: center;
    margin-top: 15px;
    font-style: italic;
}

/* ✅ Referrer Branding */
.referrer-branding {
    margin-top: 20px;
    text-align: center;
    padding: 15px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 10px;
    display: inline-block;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

/* ✅ Circular Gravatar */
.referrer-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    border: 3px solid white;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
    margin-bottom: 10px;
}

/* ✅ Referrer Name Styling */
.referrer-name {
    font-size: 16px;
    font-weight: bold;
    color: white;
    text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.5);
}

.btn-primary {
    width: 100%;
    padding: 15px;
    font-size: 20px;
    font-weight: bold;
    text-transform: uppercase;
    border: none;
    border-radius: 8px;
    background-color: <?= htmlspecialchars($leadPage['color_theme']); ?> !important;
    color: <?= ($leadPage['color_theme'] === 'yellow') ? 'black' : 'white'; ?> !important; /* ✅ Black text if yellow */
    transition: background 0.3s ease-in-out, transform 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
}


    .btn-primary:hover {
        filter: brightness(1.2);
        transform: translateY(-5px);
    }

    .btn-primary:focus, 
    .btn-primary:active {
        box-shadow: none !important;
        background-color: <?= htmlspecialchars($leadPage['color_theme']); ?> !important;
    }

    .btn-primary i {
        margin-right: 8px;
        font-family: "Font Awesome 6 Free" !important;
        font-weight: 900 !important;
    }
    
.footer {
    background-color: rgba(0, 0, 0, 0.3);
    color: white;
    text-align: center;
    padding: 15px;
    font-size: 14px;
    width: 100%;
    position: relative;
    bottom: 0;
}

        
        /* ✅ Make the main container grow to push footer down */
.main-container {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start; /* ✅ Prevents stretching */
    padding-top: min(10vh, 80px); /* ✅ Dynamic spacing at the top */
}


.mockup-column {
    flex: 1 1 400px;
    max-width: 500px;
    margin-top: 80px; /* Adjust this value to move it lower */
    padding: 10px;
}

.content-column {
    flex: 1 1 380px;
    max-width: 420px;
    background: rgba(0,0,0,0.65);
    padding: 40px;
    border-radius: 15px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.4);
    backdrop-filter: blur(5px);
    margin: 20px 0;
}

@media (max-width: 991px) {
    .mockup-column, .content-column {
        max-width: 100%;
        flex: 1 1 100%;
    }
}


.modal-content {
  animation: fadeInUp 0.6s ease;
}
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translate3d(0, 40px, 0);
  }
  to {
    opacity: 1;
    transform: translate3d(0, 0, 0);
  }
}

.modal-body {
    background: #fff !important;
    color: #333 !important;
}
.modal-body h2,
.modal-body p {
    color: #333 !important;
}
i[class*="fa-"] {
  font-family: "Font Awesome 6 Free", "Font Awesome 5 Free", "FontAwesome", sans-serif !important;
  font-weight: 900 !important;
}


#exitPopupModal h2 {
  font-weight: 800;
  color: #222;
  text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

#exitPopupModal .lead {
  font-size: 1.15rem;
  color: #555;
}

#exitPopupModal .btn-success {
  font-size: 1.1rem;
  font-weight: bold;
  letter-spacing: 0.5px;
  padding: 12px 32px;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(40, 167, 69, 0.3);
  transition: all 0.2s ease-in-out;
}

#exitPopupModal .btn-success:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 18px rgba(40, 167, 69, 0.5);
}
.lead-subheadline {
    text-align: inherit;
    color: white;
    font-family: "<?= htmlspecialchars($subheadingFont); ?>", cursive !important;
}

.lead-subheadline p {
    margin-bottom: 1rem;
}

.lead-subheadline b,
.lead-subheadline strong {
    font-weight: bold;
}

.lead-subheadline i,
.lead-subheadline em {
    font-style: italic;
}

.lead-subheadline u {
    text-decoration: underline;
}

.lead-subheadline img {
    max-width: 100%;
    height: auto;
    display: block;
    margin: 0 auto;
}

.time-box {
  border: 4px solid <?= $borderColor ?>;
  color: <?= $borderColor ?>;
}
    </style>
</head>
<body>
<?php include 'google-translate-widget-front-end.php'; ?>

<?php $hasMockup = !empty($leadPage['mockup_filename']); ?>

<!-- ✅ Begin Flex Container -->
<div class="container<?= $hasMockup ? ' d-flex align-items-start justify-content-center gap-4 flex-wrap flex-md-nowrap' : '' ?>" style="<?= $hasMockup ? 'max-width: 95%;' : '' ?>">

    <!-- ✅ Mockup Image on Left (if exists) -->
    <?php if ($hasMockup): ?>
        <div class="mockup-column text-center">
            <img src="assets/mockups/<?= htmlspecialchars($leadPage['mockup_filename']); ?>" alt="Mockup" class="img-fluid rounded shadow">
        </div>
    <?php endif; ?>

    <!-- ✅ Right Column Content -->
    <div class="<?= $hasMockup ? 'content-column' : '' ?>">

        <h1><?= htmlspecialchars($leadPage['headline']); ?></h1>
        <div class="lead-subheadline">
    <?php
echo $leadPage['subheadline'];
?>
</div>

        <!-- ✅ LeadsLeap Form (Only If User's Details Exist) -->
        <?php if (!empty($leadsleap_user_id) && !empty($leadsleap_list_id)): ?>

        <?php
        $base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);
        $redirect_url = $base_url . '/bridge.php?code=' . urlencode($share_code) . '&ref=' . urlencode($referrer);
        ?>

        <form method="post" action="https://www.sendsteed.com/subscribe/" onsubmit="storeLead(event)">
            <input name="n<?= htmlspecialchars($leadsleap_list_id); ?>" required type="text" placeholder="Enter Your Name" id="lead-name">
            <input name="e<?= htmlspecialchars($leadsleap_list_id); ?>" required type="email" placeholder="Enter Your Email" id="lead-email">

            <!-- ✅ Hidden Fields -->
            <input type="hidden" name="lllid" value="<?= htmlspecialchars($leadsleap_list_id); ?>">
            <input type="hidden" name="lluid" value="<?= htmlspecialchars($leadsleap_user_id); ?>">
            <input type="hidden" name="redirect" value="<?= htmlspecialchars($redirect_url); ?>">
            <input type="hidden" name="code" value="<?= htmlspecialchars($_GET['code'] ?? ''); ?>" id="lead-code">
            <input type="hidden" name="source" value="<?= htmlspecialchars($_GET['source'] ?? ''); ?>" id="lead-source">

<button type="submit" class="btn btn-primary">
    <i class="fas <?= htmlspecialchars($ctaIcon); ?>"></i> <?= htmlspecialchars($ctaLabel); ?>
</button>

        </form>

        <!-- ✅ Privacy -->
        <p class="privacy-disclaimer">
            We value your privacy. Your information is safe with us and will never be shared or sold.
        </p>

        <!-- ✅ Referrer Branding -->
        <?php if ($referrerData): ?>
            <div class="referrer-branding">
                <img src="<?= $gravatarURL; ?>" alt="User Avatar" class="referrer-avatar">
                <p class="referrer-name">Shared by: <strong><?= $referrerName; ?></strong></p>
            </div>
        <?php endif; ?>

        <?php else: ?>
            <p style="color: red;">No LeadsLeap integration found for this user.</p>
        <?php endif; ?>
    </div> <!-- end .content-column or main block -->

</div> <!-- end .container -->

<!-- ✅ JS: Lead Storage -->
<script>
function storeLead(event) {
    event.preventDefault();

    let name = document.getElementById("lead-name").value;
    let email = document.getElementById("lead-email").value;
    let source = document.getElementById("lead-source").value || "Direct Entry";
    let urlParams = new URLSearchParams(window.location.search);
    let ref = urlParams.get("ref");
    let code = urlParams.get("code");

    if (!name || !email || !ref || !code) {
        document.forms[0].submit();
        return;
    }

    document.querySelector("button[type='submit']").disabled = true;
    document.querySelector("button[type='submit']").innerHTML = "Submitting...";

    fetch("store_lead.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, email, ref, source, code })  
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.forms[0].submit();
        } else {
            alert("Failed to store lead internally, but continuing.");
            document.forms[0].submit();
        }
    })
    .catch(() => {
        alert("Network issue while saving lead.");
        document.forms[0].submit();
    });
}
</script>

<footer class="footer">
    &copy; <?= str_replace(['https://', 'http://', 'www.'], '', $_SERVER['HTTP_HOST']); ?>, All Rights Reserved.
</footer>





<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>

</body>
</html>
