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


if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.gc_maxlifetime', 31536000);
    ini_set('session.cookie_lifetime', 31536000);
    session_start();
}

if (!isset($_SESSION['logged_in_user'])) {
    header("Location: user-login.php");
    exit;
}


require_once 'db.php';

// ✅ Load branding name for dynamic page title + heading
$stmt = $pdo->query("SELECT brand_name FROM branding LIMIT 1");
$brandingRow = $stmt->fetch(PDO::FETCH_ASSOC);
$brandName = $brandingRow['brand_name'] ?? 'MLM Lead Pro';


function fuzzyGroup($source) {
    $s = strtolower($source);
    if (str_starts_with($s, 'tz')) return 'TrafficZest';
    if (str_starts_with($s, 'mlgs')) return 'MyLeadGenSecret';
    if (str_starts_with($s, 'llpro') || str_contains($s, 'll')) return 'LeadsLeap';
    if (str_contains($s, 'fb')) return 'Facebook';
    if (str_contains($s, 'yt')) return 'YouTube';
    if (str_contains($s, 'mlff')) return 'MultipleIncomeFunnel';
    if (str_contains($s, 'sparky')) return 'SparkyAI';
    return null;
}


try {
    // Total leads
    $stmt = $pdo->query("SELECT COUNT(*) FROM leads");
    $total_leads = $stmt->fetchColumn();

    // Total users
    $stmt = $pdo->query("SELECT COUNT(*) FROM users");
    $total_users = $stmt->fetchColumn();

    $conversion_rate = ($total_leads > 0) ? round(($total_users / $total_leads) * 100, 2) : 0;
    $avg_leads = ($total_users > 0) ? round($total_leads / $total_users, 2) : 0;
    
    // Active members = users with full setup (program, LeadsLeap ID, both lists)
$stmt = $pdo->query("
    SELECT COUNT(*) FROM user_activity
    WHERE program_ids_set = 1 AND leadsleap_id_set = 1 AND leadsleap_lists_set = 1
");
$total_active_users = $stmt->fetchColumn();

$avg_leads_per_active_user = ($total_active_users > 0) ? round($total_leads / $total_active_users, 2) : 0;


    // Top 10 by Leads
    $stmt = $pdo->query("
        SELECT u.id AS user_id, u.first_name, u.last_name, COUNT(l.id) AS lead_count
        FROM users u
        JOIN leads l ON u.id = l.user_id
        GROUP BY u.id
        ORDER BY lead_count DESC
        LIMIT 10
    ");
    $top_leads = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Top 10 by Referrals (based on referrer_id)
    $stmt = $pdo->query("
        SELECT u.id AS user_id, u.first_name, u.last_name, COUNT(r.id) AS referral_count
        FROM users u
        LEFT JOIN users r ON u.user_id = r.referrer_id
        GROUP BY u.id
        HAVING referral_count > 0
        ORDER BY referral_count DESC
        LIMIT 10
    ");
    $top_referrals = $stmt->fetchAll(PDO::FETCH_ASSOC);

    
        // ✅ Step 1: Define known aliases (clean names)
$source_aliases = [
    'fb' => 'Facebook',
    'fb1' => 'Facebook',
    'fb2' => 'Facebook',
    'fb3' => 'Facebook',
    'fb4' => 'Facebook',
    'fbreel' => 'Facebook',
    'facebook' => 'Facebook',

    'yt' => 'YouTube',
    'ytube' => 'YouTube',
    'youtube' => 'YouTube',
    'yt-vid-exedhju-j-g' => 'YouTube',

    'll' => 'LeadsLeap',
    'llpro' => 'LeadsLeap',
    'llproad' => 'LeadsLeap',
    'llproads' => 'LeadsLeap',
    'llproads2' => 'LeadsLeap',
    'llproad2' => 'LeadsLeap',
    'llproad3' => 'LeadsLeap',
    'llai' => 'LeadsLeap',
    'llreview' => 'LeadsLeap',
    'lltrack' => 'LeadsLeap',
    'lltrackinglink' => 'LeadsLeap',
    'llbanner' => 'LeadsLeap',
    'llfreeads' => 'LeadsLeap',
    'llfreeads1' => 'LeadsLeap',
    'llfunrot' => 'LeadsLeap',
    
    'tz' => 'TrafficZest',
    'tzest' => 'TrafficZest',
    'tzest1' => 'TrafficZest',
    'tzestfms' => 'TrafficZest',
    'tzestviral' => 'TrafficZest',
    'tzll' => 'TrafficZest',
    'tzcpp' => 'TrafficZest',
    'tzrt4' => 'TrafficZest',
    'tzsc' => 'TrafficZest',
    'tzmay' => 'TrafficZest',
    'tzmay-1ac1ed' => 'TrafficZest',
    'tzmay-m2g87v' => 'TrafficZest',
    'tzmay-b28395' => 'TrafficZest',
    'tz2r' => 'TrafficZest',
    'tzrt' => 'TrafficZest',
    
    'mlgs' => 'MyLeadGenSecret',
    'mlgs1' => 'MyLeadGenSecret',
    'mlgs2' => 'MyLeadGenSecret',
    'mlgs11may25' => 'MyLeadGenSecret',
    'mlgs12may25' => 'MyLeadGenSecret',
    'mlgs13may25' => 'MyLeadGenSecret',
    'mlgs14may25' => 'MyLeadGenSecret',
    'mlgs15may25' => 'MyLeadGenSecret',
    'mlgs16may25' => 'MyLeadGenSecret',
    'mlgs17may25' => 'MyLeadGenSecret',
    'mlgs18may25' => 'MyLeadGenSecret',
    'myleadgen' => 'MyLeadGenSecret',
'myleadgensecret' => 'MyLeadGenSecret',


    'mlff' => 'MultipleIncomeFunnel',
    'mlffli' => 'MultipleIncomeFunnel',

    'sparky' => 'SparkyAI',
    'sparkyai' => 'SparkyAI',

    'wpt' => 'WarriorPlus',

    'direct entry' => 'Direct Entry',
    'direct' => 'Direct Entry',

    'zest' => 'TrafficZest',
    'rb' => 'Rotator',
    'rotatorpage' => 'Rotator',
    'giosolo' => 'Solo Ads',
    'scale' => 'Scaling Funnels',
    'scaleup' => 'Scaling Funnels',
    'scalelup' => 'Scaling Funnels',
    'scaleiup' => 'Scaling Funnels',
    'm3' => 'Scaling Funnels',
    'lp1' => 'Landing Pages',
    'ailp' => 'Landing Pages',
    'tct' => 'Custom Tracking',
    'tctai' => 'Custom Tracking',
    'tctgf' => 'Custom Tracking',
    'tctfvms' => 'Custom Tracking',
    'tctpp' => 'Custom Tracking',
    'em' => 'Email Traffic',
    'mailgold' => 'Email Traffic',
    'mailerplus' => 'Email Traffic',
    'mailsy' => 'Email Traffic',
    'send' => 'Email Traffic',
    'email' => 'Email Traffic',
    'gmass' => 'Email Traffic',
    'leapfrog' => 'Bonus Funnel',
    'referralfrenzy' => 'Referral Frenzy',
    'frenzy1' => 'Referral Frenzy',
    'frenzy2' => 'Referral Frenzy',
    'linked' => 'LinkedIn',
    'linkedad1' => 'LinkedIn'
];


    // ✅ Step 2: Fetch raw source counts from leads table
    $stmt = $pdo->query("SELECT source, COUNT(*) AS count FROM leads GROUP BY source");
    $raw_sources = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // ✅ Step 3: Process sources with alias map
    $cleaned_sources = [];

    foreach ($raw_sources as $row) {
        $raw = strtolower(trim($row['source']));
            $alias = $source_aliases[$raw] ?? fuzzyGroup($raw) ?? $raw;
$alias = ucwords(strtolower($alias));
 // fallback to capitalized raw

        if (!isset($cleaned_sources[$alias])) {
            $cleaned_sources[$alias] = 0;
        }

        $cleaned_sources[$alias] += $row['count'];
    }

    // ✅ Step 4: Sort by count descending
    arsort($cleaned_sources);


} catch (Exception $e) {
    die("Something went wrong: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html>
<head>
    <title><?= htmlspecialchars($brandName); ?> - Global Stats</title>
    <meta charset="UTF-8">
    <!-- Fonts + Bootstrap -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<!-- Optional: FontAwesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">

    <style>
                .box { max-width: 850px; background: white; margin: auto; padding: 30px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        h2, h3 { margin-top: 0; }
        ul, ol { padding-left: 20px; }
        li { margin-bottom: 8px; }
        
        .btn-success {
    background-color: #28a745;
    color: white;
    border: none;
}
.btn-success:hover {
    background-color: #218838;
    color: white;
}

body {
    font-family: 'Inter', sans-serif;
    background-color: #f4f6f9;
    padding: 40px 15px;
}

.container-box {
    max-width: 1100px; /* ✅ Limits width nicely even on big screens */
    margin: auto;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 8px 20px rgba(0,0,0,0.05);
    padding: 30px 35px;
    margin-bottom: 40px;
}


h2, h3, h4 {
    font-weight: 700;
    color: #333;
}

.section-divider {
    border-top: 2px dashed #ddd;
    margin: 40px 0;
}

.stats-highlight {
    font-size: 18px;
    font-weight: 600;
    color: #0055ff;
}

.badge-icon {
    font-size: 20px;
    margin-right: 6px;
}
.text-shadow {
    text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.8);
}
@media (max-width: 576px) {
    h2 {
        font-size: 1.5rem;
    }
    .card-title {
        font-size: 1rem;
    }
    .card-text .badge {
        font-size: 0.9rem;
    }
}
.banner-wrapper {
    max-width: 100%;
    display: block;
    text-align: center;
    padding-left: 10px;
    padding-right: 10px;
}

details summary {
    cursor: pointer;
    font-weight: 600;
    background-color: #f0f4ff;
    padding: 12px 18px;
    border-radius: 8px;
    border: 1px solid #c7dfff;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    margin-bottom: 10px;
    transition: all 0.2s ease;
}

details[open] summary {
    background-color: #e2edff;
    border-color: #9cc0ff;
}

details summary::marker {
    font-size: 1.2em;
    color: #0055ff;
}
details[open] ul {
    animation: fadeIn 0.25s ease-in;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-5px); }
    to { opacity: 1; transform: translateY(0); }
}


.video-wrapper {
    margin: 30px auto;
    max-width: 900px;
    padding: 20px 25px;
    background: #f9faff;
    border: 1px solid #dde7ff;
    border-radius: 12px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.03);
}

.video-header h5 {
    font-size: 1.25rem;
}

.video-container {
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    overflow: hidden;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.video-container iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 8px;
}

    </style>
</head>
<body>



    <div class="container-box">
    
<div class="banner-wrapper mb-4">
    <img src="assets/images/global-stats-banner.jpg" class="img-fluid rounded shadow-sm w-100" alt="Global Stats Banner">
</div>




        <h2 class="mt-2 mb-4 text-center">📊 <?= htmlspecialchars($brandName); ?> Global Stats <small class="text-muted">(<?= date('F j, Y'); ?>)</small></h2>
        
        
        <div class="video-wrapper mb-4">
  <div class="video-header text-center mb-3">
    <h5 class="text-primary fw-semibold mb-1">🎥 How to Use This Stats Page</h5>
    <p class="text-muted small">Watch this quick walkthrough to understand how to get the most out of the global stats dashboard.</p>
  </div>
  <div class="video-container">
    <iframe src="https://www.loom.com/embed/06ac7004576e446d819ca219e8e6323c?sid=b23e5760-847e-477c-8db9-492f3653a94a"
            frameborder="0" 
            webkitallowfullscreen 
            mozallowfullscreen 
            allowfullscreen>
    </iframe>
  </div>
</div>

        
        <ul>
            <li><strong>Total Leads:</strong> <?= number_format($total_leads); ?></li>
            <li><strong>Total Members:</strong> <?= number_format($total_users); ?></li>
            <li><strong>Global Conversion Rate:</strong> <?= $conversion_rate; ?>%</li>
            <li><strong>Average Leads per Active Member:</strong> <?= $avg_leads_per_active_user; ?> 
</li>

        </ul>

<h3>🏆 Top 10 Members by Leads</h3>
<div class="row">
<?php
function getLeadBadge($rank) {
    return match ($rank) {
        1 => '👑',
        2 => '🥈',
        3 => '🥉',
        default => '🔥',
    };
}

$i = 1;
foreach ($top_leads as $row):
    $badge = getLeadBadge($i);
?>
    <div class="col-md-6 col-lg-4 mb-4">
        <div class="card shadow-sm h-100">
            <div class="card-body">
                <h5 class="card-title"><?= $badge ?> <?= htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?></h5>
                <p class="card-text"><span class="badge bg-primary">Leads: <?= $row['lead_count']; ?></span></p>
            </div>
        </div>
    </div>
<?php $i++; endforeach; ?>
</div>



        <h3>🚀 Top 10 Members by Referrals</h3>
        <ol>
            <?php foreach ($top_referrals as $row): ?>
                <li>
                    <strong><?= htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?> :</strong>
                    <?= $row['referral_count']; ?> referrals
                </li>
            <?php endforeach; ?>
        </ol>
        
 <h3>📈 Top Lead Sources (Clean View)</h3>
<ul>
<?php
$icons = [
    'TrafficZest' => '🚦',
    'LeadsLeap' => '🔁',
    'YouTube' => '📺',
    'Facebook' => '📘',
    'Email Traffic' => '📧',
    'Rotator' => '🎯',
    'Direct Entry' => '🔓',
    'MultipleIncomeFunnel' => '🔂',
    'WarriorPlus' => '⚔️',
];

foreach ($cleaned_sources as $label => $count) {
    $normalizedLabel = strtolower($label);
    $matchFound = false;
    $iconKey = '';

    foreach ($icons as $iconLabel => $iconSymbol) {
        if (strtolower($iconLabel) === $normalizedLabel) {
            $matchFound = true;
            $iconKey = $iconLabel;
            $icon = $iconSymbol;
            break;
        }
    }

    if (!$matchFound) continue;

    $emailStmt = $pdo->prepare("
        SELECT DISTINCT email FROM leads WHERE LOWER(TRIM(source)) = ?
    ");
    $emailStmt->execute([$normalizedLabel]);
    $emails = $emailStmt->fetchAll(PDO::FETCH_COLUMN);

    if (empty($emails)) {
        echo "<li><strong>$icon $iconKey:</strong> " . number_format($count) . " leads — ❌ 0 signups (0%)</li>";
        continue;
    }

    $placeholders = implode(',', array_fill(0, count($emails), '?'));
    $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email IN ($placeholders)");
    $checkStmt->execute($emails);
    $convertedCount = $checkStmt->fetchColumn();
    $rate = $count > 0 ? round(($convertedCount / $count) * 100, 2) : 0;

    echo "<li><strong>$icon $iconKey:</strong> " .
         number_format($count) . " leads — ✅ $convertedCount signups ($rate%)</li>";
}

?>
</ul>


<?php
// ✅ Load logged-in user ID
$loggedInUser = $_SESSION['logged_in_user'] ?? null;

// ✅ Default fallback TrafficZest ID
$defaultTrafficZestID = '16ad74f0-1fbc-43b8-a9e8-7c8c91f7e6c3';
$referrerTrafficZestID = $defaultTrafficZestID;
$userTrafficZestID = '';

// ✅ If logged in, fetch user's and sponsor's TrafficZest ID
if ($loggedInUser) {
    // Get user's TrafficZest ID
    $stmt = $pdo->prepare("SELECT trafficzest_user_id, referrer_id FROM users WHERE user_id = ?");
    $stmt->execute([$loggedInUser]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    $userTrafficZestID = $row['trafficzest_user_id'] ?? '';
    $referrerId = $row['referrer_id'] ?? null;

    // If referrer exists, try to use their TrafficZest ID
    if ($referrerId) {
        $stmt = $pdo->prepare("SELECT trafficzest_user_id FROM users WHERE user_id = ?");
        $stmt->execute([$referrerId]);
        $sponsorID = $stmt->fetchColumn();
        if (!empty($sponsorID)) {
            $referrerTrafficZestID = $sponsorID;
        }
    }
}

// ✅ Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_trafficzest_id'])) {
    $newID = trim($_POST['trafficzest_user_id'] ?? '');
    $stmt = $pdo->prepare("UPDATE users SET trafficzest_user_id = ? WHERE user_id = ?");
    $stmt->execute([$newID, $loggedInUser]);
    $userTrafficZestID = $newID;
    echo "<div class='alert alert-success' style='margin-top: 20px;'>✅ Your TrafficZest ID has been saved!</div>";
}
?>

<!-- 🌟 TrafficZest Promo Section -->
<div style="margin-top: 40px; padding: 25px; border: 2px dashed #ccc; border-radius: 12px; background: #fefefe; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
    <h3 style="margin-top: 0;">🚦 TrafficZest Is On Fire!</h3>
    <p>With <strong>1,900+ leads</strong> and hundreds of signups, TrafficZest is one of our most powerful traffic platforms.</p>

    <?php if (empty($userTrafficZestID)): ?>
        <p><strong>Step 1:</strong> Join using your sponsor’s referral link below:</p>
        <a href="https://trafficzest.com/?rft1=<?= htmlspecialchars($referrerTrafficZestID); ?>" 
           class="btn btn-success" 
           style="padding: 12px 25px; font-size: 16px; border-radius: 8px; text-decoration: none; display: inline-block; margin-bottom: 20px;" 
           target="_blank" rel="noopener noreferrer">
            ✅ Join TrafficZest Now
        </a>
    <?php else: ?>
        <p>✅ You’ve already added your TrafficZest ID. Your team will join using your referral link.</p>
    <?php endif; ?>

    <form method="POST" style="margin-top: 20px;">
        <input type="hidden" name="save_trafficzest_id" value="1">
        <label for="trafficzest_user_id"><strong>Step 2:</strong> Paste your TrafficZest User ID here:</label><BR>
        <input type="text" name="trafficzest_user_id" class="form-control" 
               value="<?= htmlspecialchars($userTrafficZestID); ?>" 
               placeholder="Paste your TrafficZest ID like: 16ad74f0-..." 
               style="margin: 10px 0; padding: 10px; border-radius: 6px; width: 100%; max-width: 400px;">
        <button type="submit" class="btn btn-primary" style="padding: 8px 20px;">
            💾 Save My TrafficZest ID
        </button>
    </form>
<?php if (!empty($userTrafficZestID)): ?>
    <div style="margin-top: 20px; padding: 15px; background: #e6f7ff; border: 1px solid #b3e5fc; border-radius: 8px;">
        <strong>🔗 Your TrafficZest Referral Link Preview:</strong>
        <p style="margin: 8px 0 12px; color: #333;">This is what your referrals will see when they join through your link.</p>
        <a href="https://trafficzest.com/?rft1=<?= htmlspecialchars($userTrafficZestID); ?>" 
           class="btn btn-info"
           style="display: inline-block; padding: 10px 20px; font-size: 15px; text-decoration: none; border-radius: 6px;"
           target="_blank" rel="noopener noreferrer">
           🔍 Test My TrafficZest Link
        </a>
    </div>
<?php endif; ?>



</div>



<details style="margin-top:20px;">
<summary>📂 Show All Raw Traffic Sources (Unfiltered)</summary>
<ul>
<?php
// 🧭 RAW / Unfiltered section – EXCLUDES cleanView icons
foreach ($cleaned_sources as $label => $count) {
    $normalizedLabel = strtolower($label);

    // Skip if label is already in icons array (shown above in Clean View)
    $alreadyShown = false;
    foreach ($icons as $iconLabel => $iconSymbol) {
        if (strtolower($iconLabel) === $normalizedLabel) {
            $alreadyShown = true;
            break;
        }
    }
    if ($alreadyShown) continue;

    $icon = '🧭';

    $emailStmt = $pdo->prepare("
        SELECT DISTINCT email FROM leads WHERE LOWER(TRIM(source)) = ?
    ");
    $emailStmt->execute([$normalizedLabel]);
    $emails = $emailStmt->fetchAll(PDO::FETCH_COLUMN);

    if (empty($emails)) {
        echo "<li><strong>$icon $label:</strong> " . number_format($count) . " leads — ❌ 0 signups (0%)</li>";
        continue;
    }

    $placeholders = implode(',', array_fill(0, count($emails), '?'));
    $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email IN ($placeholders)");
    $checkStmt->execute($emails);
    $convertedCount = $checkStmt->fetchColumn();
    $rate = $count > 0 ? round(($convertedCount / $count) * 100, 2) : 0;

    echo "<li><strong>$icon $label:</strong> " .
         number_format($count) . " leads — ✅ $convertedCount signups ($rate%)</li>";
}
?>

</ul>
</details>



<h3>👑 Top Performing Members by Traffic Source</h3>

<?php
$topSources = ['TrafficZest', 'LeadsLeap', 'YouTube'];
$sourceLeaders = [];

// Get top 200 rows across all sources first for performance
$stmt = $pdo->query("
    SELECT 
        l.page_id,
        l.source,
        COUNT(*) AS lead_count,
        u.first_name,
        u.last_name,
        p.headline
    FROM leads l
    JOIN users u ON l.user_id = u.id
    JOIN lead_capture_pages p ON l.page_id = p.id
    GROUP BY l.page_id, l.source
    HAVING lead_count >= 25
    ORDER BY lead_count DESC
    LIMIT 200
");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$allowedSources = ['trafficzest', 'leadsleap', 'youtube']; // all lowercase for reliable comparison

foreach ($rows as $row) {
    $rawSource = strtolower(trim($row['source']));
    $cleanSource = $source_aliases[$rawSource] ?? fuzzyGroup($rawSource) ?? ucwords($rawSource);

    $normalizedSource = strtolower($cleanSource); // normalize to lowercase for comparison

    if (!in_array($normalizedSource, $allowedSources)) continue;


    // Count how many of these leads converted
    $emailStmt = $pdo->prepare("
        SELECT COUNT(*) FROM users 
        WHERE email IN (
            SELECT email FROM leads 
            WHERE page_id = ? AND source = ?
        )
    ");
    $emailStmt->execute([$row['page_id'], $row['source']]);
    $converted = $emailStmt->fetchColumn();

    $conversionRate = $row['lead_count'] > 0 ? round(($converted / $row['lead_count']) * 100, 2) : 0;

    $sourceLeaders[$normalizedSource][] = [
        'name' => $row['first_name'] . ' ' . $row['last_name'],
        'headline' => $row['headline'],
        'leads' => $row['lead_count'],
        'signups' => $converted,
        'rate' => $conversionRate
    ];
}
?>

<?php foreach (array_keys($sourceLeaders) as $source): ?>
    <?php if (!empty($sourceLeaders[$source])): ?>
        <h4 style="margin-top: 20px;">
    <?= htmlspecialchars(ucwords(strtolower($source))); ?>
</h4>
        <ul>
            <?php foreach ($sourceLeaders[$source] as $entry): ?>
                <li>
                    <strong><?= htmlspecialchars($entry['name']); ?>:</strong>
                    <?= $entry['leads']; ?> leads,
                    <?= $entry['signups']; ?> signups
                    (<?= $entry['rate']; ?>%)
                </li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>
<?php endforeach; ?>

        
<h3>🔍 Capture Page + Source Breakdown (Top 50)</h3>
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover align-middle mt-4">
    <thead style="background: #f0f0f0;">
        <tr>
            <th>Funnel Owner</th>
            <th>Capture Page Headline</th>
            <th>Source</th>
            <th>Leads</th>
            <th>% of Total</th>
            <th>Converted?</th>
        </tr>
    </thead>
    <tbody>
        <?php
        $stmt = $pdo->query("
            SELECT 
                l.page_id,
                l.source,
                COUNT(*) AS lead_count,
                u.first_name,
                u.last_name,
                p.share_code,
                p.headline
            FROM leads l
            JOIN users u ON l.user_id = u.id
            JOIN lead_capture_pages p ON l.page_id = p.id
            GROUP BY l.page_id, l.source
            ORDER BY lead_count DESC
            LIMIT 50
        ");
        $pageSourceCombos = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($pageSourceCombos as $row) {
            $cleanSource = $source_aliases[strtolower($row['source'])] ?? fuzzyGroup($row['source']) ?? $row['source'];
            $percent = $total_leads > 0 ? round(($row['lead_count'] / $total_leads) * 100, 2) : 0;
            
                // NEW: Count how many of this lead group converted
    $emailCheckStmt = $pdo->prepare("
        SELECT COUNT(*) FROM users 
        WHERE email IN (
            SELECT email FROM leads 
            WHERE page_id = ? AND source = ?
        )
    ");
    $emailCheckStmt->execute([$row['page_id'], $row['source']]);
    $convertedCount = $emailCheckStmt->fetchColumn();
            
            echo "<tr>";
            echo "<td>" . htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) . "</td>";
            echo "<td>" . htmlspecialchars($row['headline']) . "</td>";
            echo "<td>" . htmlspecialchars($cleanSource) . "</td>";
            echo "<td>" . $row['lead_count'] . "</td>";
            echo "<td>" . $percent . "%</td>";
            $conversionRate = $row['lead_count'] > 0 ? round(($convertedCount / $row['lead_count']) * 100, 2) : 0;
echo "<td>" . $convertedCount . " / " . $row['lead_count'] . " (" . $conversionRate . "%)</td>";
 // ← NEW
            echo "</tr>";
        }
        ?>
    </tbody>
</table>
</div>


    </div>
    
    <div style="
    max-width: 850px;
    margin: 40px auto 0;
    background: #222;
    color: #ccc;
    padding: 20px 25px;
    border-radius: 10px;
    font-size: 14px;
    line-height: 1.6;
    box-shadow: 0 0 10px rgba(0,0,0,0.3);
    text-align: center;
">
<?php include 'footer.php'; ?>
    </span>
</div>

<script>
function copyToClipboard(elementId) {
    const input = document.getElementById(elementId);
    input.select();
    input.setSelectionRange(0, 99999); // for mobile compatibility
    navigator.clipboard.writeText(input.value).then(() => {
        alert("✅ Link copied to clipboard!");
    });
}
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>
