<?php
// At the top of your file (keep logging on, but suppress Warnings visually)
error_reporting(E_ALL & ~E_WARNING);
ini_set('display_errors', 1); // still shows other critical errors
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error_log.txt');



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

require_once 'db.php';


// ✅ Load strategy templates
$strategyTemplatesPath = __DIR__ . '/rb/data/templates-v2.json';
$strategyTemplates = json_decode(file_get_contents($strategyTemplatesPath), true) ?? [];




// ✅ Load Steps and check for Step 3 override
$stmt = $pdo->query("SELECT * FROM programs ORDER BY slot_number ASC LIMIT 4");
$steps = $stmt->fetchAll(PDO::FETCH_ASSOC);



// ✅ STATIC LABEL OVERRIDE FOR STEP 3 (based on logged-in user's SPONSOR settings)
if (isset($_SESSION['logged_in_user'])) {
    $loggedInUser = $_SESSION['logged_in_user'];

    // Get referrer of logged-in user
    $stmt = $pdo->prepare("SELECT referrer_id FROM users WHERE user_id = ?");
    $stmt->execute([$loggedInUser]);
    $referrerID = $stmt->fetchColumn();

    if (!empty($referrerID)) {
        $stmt = $pdo->prepare("SELECT override_dashboard_step, override_program_slot, id FROM users WHERE user_id = ?");
        $stmt->execute([$referrerID]);
        $sponsor = $stmt->fetch(PDO::FETCH_ASSOC);

        if (
            $sponsor &&
            (int)$sponsor['override_dashboard_step'] === 3 &&
            (int)$sponsor['override_program_slot'] > 0
        ) {
            $slotIndex = (int)$sponsor['override_program_slot'] - 1;

            $stmt = $pdo->prepare("SELECT program_name FROM user_programs WHERE user_id = ? ORDER BY id ASC");
            $stmt->execute([$sponsor['id']]);
            $sponsorPrograms = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if (!empty($sponsorPrograms[$slotIndex]['program_name']) && isset($steps[2])) {
                $steps[2]['step_label'] = $sponsorPrograms[$slotIndex]['program_name'];
            }
        }
    }
}


// ✅ Track login + basic setup progress
$userId = $_SESSION['logged_in_user'] ?? null;

if ($userId) {
    // Get user info
    $stmt = $pdo->prepare("SELECT id, leadsleap_user_id, leadsleap_list_id, leadsleap_list_id_referrals FROM users WHERE user_id = ?");

    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        $numericId = $user['id'];
        $leadsleapSet = !empty($user['leadsleap_user_id']);
        $campaign1Set = !empty($user['leadsleap_list_id']);
$campaign2Set = !empty($user['leadsleap_list_id_referrals']);

if ($campaign1Set && $campaign2Set) {
    $leadsleapListsSet = 1; // ✅
} elseif ($campaign1Set || $campaign2Set) {
    $leadsleapListsSet = -1; // ⚠️
} else {
    $leadsleapListsSet = 0; // ❌
}

        // Count filled core programs
        $stmt = $pdo->prepare("SELECT * FROM users WHERE user_id = ?");
        $stmt->execute([$userId]);
        $core = $stmt->fetch(PDO::FETCH_ASSOC);
        $coreProgramSet = false;
        for ($i = 1; $i <= 10; $i++) {
            $key = 'program_' . $i;
            if (!empty($core[$key])) {
                $coreProgramSet = true;
                break;
            }
        }

        // Insert or update activity safely
        $stmt = $pdo->prepare("SELECT user_id FROM user_activity WHERE user_id = ?");
        $stmt->execute([$userId]);

        if ($stmt->rowCount()) {
// 🟠 Determine campaign status with 3 states
$campaign1Set = !empty($user['leadsleap_list_id']);
$campaign2Set = !empty($user['leadsleap_list_id_referrals']);

if ($campaign1Set && $campaign2Set) {
    $leadsleapListsSet = 1; // ✅ Both
} elseif ($campaign1Set || $campaign2Set) {
    $leadsleapListsSet = -1; // ⚠️ One
} else {
    $leadsleapListsSet = 0; // ❌ None
}

// 🔄 Update activity row with partial status logic
$stmt = $pdo->prepare("UPDATE user_activity SET 
    logins = logins + 1, 
    last_login = NOW(), 
    leadsleap_id_set = ?, 
    leadsleap_lists_set = ?, 
    program_ids_set = ?
    WHERE user_id = ?");
$stmt->execute([$leadsleapSet, $leadsleapListsSet, $coreProgramSet, $userId]);

        } else {
$stmt = $pdo->prepare("INSERT INTO user_activity 
    (user_id, leadsleap_id_set, leadsleap_lists_set, program_ids_set) 
    VALUES (?, ?, ?, ?)");
$stmt->execute([$userId, $leadsleapSet, $bothCampaignsSet, $coreProgramSet]);

        }
    }
}


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

$loggedInUser = $_SESSION['logged_in_user'];



// ✅ Ensure we're using the correct numeric user ID
$stmt = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$loggedInUserID = $stmt->fetchColumn();

// ✅ STEP 1: Setup Progress Checks

// Count only joinable programs (those with {{USER_ID}} in url_template)
$stmt = $pdo->query("SELECT COUNT(*) FROM programs WHERE url_template LIKE '%{{USER_ID}}%'");
$totalPrograms = $stmt->fetchColumn();

// Fetch current user's programs, autoresponder info, etc.
$stmt = $pdo->prepare("SELECT * FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$userData = $stmt->fetch(PDO::FETCH_ASSOC);

// Programs Joined
$programsJoined = 0;
for ($i = 1; $i <= 10; $i++) {
    $key = "program_$i";
    if (!empty($userData[$key])) {
        $programsJoined++;
    }
}
$programsJoined = min($programsJoined, $totalPrograms); // Cap to number of active programs

// Autoresponder Setup
$autoresponderList1 = $userData['leadsleap_list_id'] ?? '';
$autoresponderList2 = $userData['leadsleap_list_id_referrals'] ?? '';
$autoresponderComplete = (!empty($autoresponderList1) && !empty($autoresponderList2));


$missingLeadsLeap = empty($user['leadsleap_user_id']) || empty($user['leadsleap_list_id']);


// Own Programs Count
$stmt = $pdo->prepare("SELECT COUNT(*) FROM user_programs WHERE user_id = ?");
$stmt->execute([$loggedInUserID]);
$ownProgramsAdded = $stmt->fetchColumn();

// Referral Link Created
$stmt = $pdo->prepare("SELECT COUNT(*) FROM lead_capture_pages WHERE user_id = ?");
$stmt->execute([$loggedInUserID]);
$referralLinkCreated = $stmt->fetchColumn() > 0;


// ✅ Fetch user activity for badge display
$stmt = $pdo->prepare("SELECT * FROM user_activity WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$activity = $stmt->fetch(PDO::FETCH_ASSOC);

// ✅ Corrected active check
$isActive = (
    isset($activity['program_ids_set'], $activity['leadsleap_id_set'], $activity['leadsleap_lists_set']) &&
    $activity['program_ids_set'] == 1 &&
    $activity['leadsleap_id_set'] == 1 &&
    $activity['leadsleap_lists_set'] == 1
);

$badgeFilename = $isActive ? 'badge-active.png' : 'badge-inactive.png';
$badgeStatusText = $isActive ? 'Active User' : 'Inactive User';



// ✅ Fetch Logo and brand name from Database (Make sure 'settings' is your actual table name)
$stmt = $pdo->prepare("SELECT logo_image, brand_name FROM branding WHERE id = 1");
$stmt->execute();
$settings = $stmt->fetch(PDO::FETCH_ASSOC);

$logoImage = !empty($settings['logo_image']) ? $settings['logo_image'] : '';
$brandName = !empty($settings['brand_name']) ? $settings['brand_name'] : 'MLM Lead Pro';




// ✅ Fetch Total Referrals
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE referrer_id = ?");
$stmt->execute([$loggedInUser]);
$totalReferrals = $stmt->fetchColumn();



if (!$loggedInUserID) {
    $loggedInUserID = 0; // Fallback to prevent errors
}

// ✅ Fetch Total Leads using numeric user ID
$stmt = $pdo->prepare("SELECT COUNT(*) FROM leads WHERE user_id = ?");
$stmt->execute([$loggedInUserID]);
$totalLeads = $stmt->fetchColumn();

// ✅ Fetch total clicks
$stmt = $pdo->prepare("SELECT COUNT(*) FROM clicks WHERE user_id = ?");
$stmt->execute([$loggedInUserID]);
$totalClicks = $stmt->fetchColumn();




// ✅ Fetch Latest Signups with Email (Filtered by Logged-in User)
$stmt = $pdo->prepare("SELECT first_name, last_name, email FROM users WHERE referrer_id = ? ORDER BY created_at DESC LIMIT 5");
$stmt->execute([$loggedInUser]);
$latestSignups = $stmt->fetchAll(PDO::FETCH_ASSOC);


function getStrategySlugByUser($userId, $templates) {
    $slugPrefix = 'strategy-' . $userId . '-';
    $matching = [];

    foreach ($templates as $slug => $data) {
        if (str_starts_with($slug, $slugPrefix)) {
            $matching[$slug] = $data;
        }
    }

    if (!empty($matching)) {
        // Flip order and return the latest one
        $matching = array_reverse($matching, true);
        $latestSlug = array_key_first($matching);
        return [
            'slug' => $latestSlug,
            'ref_id' => $matching[$latestSlug]['default_ref_id'] ?? $userId
        ];
    }

    return null;
}



// ✅ Fetch Leaderboard (excluding demo and admin accounts)
$stmt = $pdo->query("
    SELECT u.first_name, u.last_name, u.email, COUNT(r.user_id) AS referral_count 
    FROM users u 
    LEFT JOIN users r ON u.user_id = r.referrer_id 
    WHERE COALESCE(u.is_demo, 0) = 0
    GROUP BY u.user_id 
    ORDER BY referral_count DESC 
    LIMIT 25
");
$leaderboard = $stmt->fetchAll(PDO::FETCH_ASSOC); // ✅ <-- This line is CRUCIAL


// ✅ Get Sponsor (Referrer)
$stmt = $pdo->prepare("SELECT referrer_id FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$referrerID = $stmt->fetchColumn();

$sponsorName = "No Sponsor";
$sponsorEmail = "N/A";
$sponsorProfileImage = "assets/images/default-user-profile-image.png"; // Default image

if (!empty($referrerID)) {
    $stmt = $pdo->prepare("SELECT first_name, last_name, email, profile_video_url FROM users WHERE user_id = ?");
    $stmt->execute([$referrerID]);
    $sponsor = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($sponsor) {
        $sponsorName = trim(($sponsor['first_name'] ?? '') . " " . ($sponsor['last_name'] ?? ''));
        $sponsorName = !empty($sponsorName) ? $sponsorName : "No Sponsor"; 
        $sponsorEmail = htmlspecialchars($sponsor['email'] ?? "N/A");
        $sponsorVideoURL = $sponsor['profile_video_url'] ?? null;

        // Generate Gravatar URL based on email
        $gravatarHash = md5(strtolower(trim($sponsor['email'])));
        $gravatarURL = "https://www.gravatar.com/avatar/$gravatarHash?s=200&d=404";
        $headers = @get_headers($gravatarURL);
        if ($headers && strpos($headers[0], '200')) {
            $sponsorProfileImage = $gravatarURL;
        }
    }
}


// ✅ Fetch Sponsor's Programs
$sponsorPrograms = [];
if (!empty($referrerID)) {
    $stmt = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
    $stmt->execute([$referrerID]);
    $sponsor = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($sponsor && isset($sponsor['id'])) {
        $sponsor_id = $sponsor['id'];

        $stmt = $pdo->prepare("SELECT * FROM user_programs WHERE user_id = ?");
        $stmt->execute([$sponsor_id]);
        $sponsorPrograms = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}



// ✅ Generate Dynamic Referral Link
// ✅ Define the base URL correctly
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$dir = rtrim(dirname($_SERVER['PHP_SELF']), '/');
$baseURL = $protocol . "://" . $_SERVER['HTTP_HOST'] . $dir;

// ✅ SAFE AUTO-CLONE DEFAULT CAPTURE PAGE ONLY IF USER STILL EXISTS
$stmt = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$loggedInUserID = $stmt->fetchColumn();

if ($loggedInUserID) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM lead_capture_pages WHERE user_id = ? AND default_capture = 1");
    $stmt->execute([$loggedInUserID]);
    $hasDefaultCapture = $stmt->fetchColumn();

    if ($hasDefaultCapture == 0) {
// ✅ Load default share code from branding settings
$brandingStmt = $pdo->query("SELECT default_share_code FROM branding WHERE id = 1");
$brandingData = $brandingStmt->fetch(PDO::FETCH_ASSOC);
$defaultShareCode = $brandingData['default_share_code'] ?? null;

if ($defaultShareCode) {
    $stmt = $pdo->prepare("SELECT * FROM lead_capture_pages WHERE share_code = ? LIMIT 1");
    $stmt->execute([$defaultShareCode]);
    $template = $stmt->fetch(PDO::FETCH_ASSOC);
}


        if ($template) {
            $newShareCode = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), 0, 6); // e.g. "C9GK2P"

$insert = $pdo->prepare("
    INSERT INTO lead_capture_pages 
    (user_id, share_code, layout, background, mockup_filename, color_theme, headline, subheadline, footer_text, form_name_field, created_at, thumbnail, font_headline, font_subheading, default_capture, cta_text, exit_popup_enabled, exit_popup_lead_magnet_id)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?, ?, 1, ?, ?, ?)
");

$insert->execute([
    $loggedInUserID,
    $newShareCode,
    $template['layout'],
    $template['background'],
    $template['mockup_filename'] ?? $template['mockup'],  // fallback for legacy
    $template['color_theme'],
    $template['headline'],
    $template['subheadline'],
    $template['footer_text'],
    $template['form_name_field'],
    $template['thumbnail'],
    $template['font_headline'],
    $template['font_subheading'],
    $template['cta_text'] ?? '',
    $template['exit_popup_enabled'] ?? 0,
    $template['exit_popup_lead_magnet_id'] ?? null
]);
        }
    }
} else {
    // ⛔ Prevents error if user was deleted
    error_log("⚠️ Tried to clone capture page for deleted or invalid user: $loggedInUser");
}


// Now fetch the default lead capture page using the numeric user ID
$stmt = $pdo->prepare("SELECT share_code FROM lead_capture_pages WHERE user_id = ? AND default_capture = 1 LIMIT 1");
$stmt->execute([$loggedInUserID]);
$defaultCapturePage = $stmt->fetch(PDO::FETCH_ASSOC);


if (!empty($defaultCapturePage['share_code'])) {
    // ✅ Use the selected lead capture page
    $referralLink = $baseURL . "/lead.php?code=" . 
        htmlspecialchars($defaultCapturePage['share_code']) . "&ref=" . 
        htmlspecialchars($loggedInUser);
} else {
    $referralLink = null; // Don't set a link if no default exists
}

?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title><?= htmlspecialchars($brandName); ?> - Dashboard</title>
    <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">
    
    <!-- Add this inside the <head> section -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intro.js/7.1.0/introjs.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/intro.js/7.1.0/intro.min.js"></script>
<link rel="stylesheet" href="assets/css/nav-style.css?v=2">

<link rel="apple-touch-icon" href="/assets/icons/icon-192x192.png">
<link rel="apple-touch-icon" sizes="512x512" href="/assets/icons/icon-512x512.png">



    
    
    <style>
    
    body {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

.container-fluid {
    flex-grow: 1;
}


    /* Ensure the sidebar stays fixed properly */
    .sidebar {
        width: 250px !important;
        min-height: 100vh;
        background-color: #f8f9fa;
    }

    /* Fix the main content so it doesn't shrink */
    .container-fluid {
        flex-grow: 1 !important;
        padding: 20px !important;
    }

    /* Ensure widgets and buttons stay aligned */
    .card {
        border-radius: 10px !important;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;
    }

    /* Fix footer width */
    footer {
        width: 100% !important;
    }
    
    /* Floating Copy Notification */
.copy-notification {
    position: fixed;
    bottom: 30px;
    left: 50%;
    transform: translateX(-50%);
    background-color: #28a745;
    color: white;
    padding: 10px 20px;
    border-radius: 8px;
    font-size: 16px;
    display: none;
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.2);
    z-index: 1000;
    transition: opacity 0.5s ease-in-out;
}



.copy-notification.show {
    display: block;
    opacity: 1;
}

.copy-notification i {
    margin-right: 8px;
}

/* Footer */
.footer {
    background-color: #343a40; /* Dark background */
    color: #ffffff; /* White text */
    text-align: center;
    padding: 15px;
    font-size: 14px;
    width: 100%;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    position: relative; /* Ensures it stays below content */
    margin-top: 20px; /* Adds space above the footer */
}

.rounded-circle {
    border-radius: 50%;
    object-fit: cover;
}

.quick-tour-btn {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background-color: #17a2b8; 
    color: white;
    border: none;
    padding: 12px 18px;
    border-radius: 5px;
    font-size: 14px;
    cursor: pointer;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
    transition: background-color 0.3s ease-in-out;
    z-index: 1000;
}

.quick-tour-btn:hover {
    background-color: #138496;
}

/* Small "X" button to hide */
.hide-tour-btn {
    position: fixed;
    bottom: 75px; /* Moves it slightly above the "Take a Quick Tour" button */
    right: 20px; /* Aligns it with the floating button */
    background-color: transparent;
    color: #666;
    border: none;
    font-size: 18px;
    cursor: pointer;
    z-index: 1001; /* Ensures it's always clickable */
}

.hide-tour-btn:hover {
    color: #000;
}


.reset-tour-btn {
    position: fixed;
    bottom: 20px;
    left: 20px;
    background-color: #f39c12; /* Orange */
    color: white;
    border: none;
    padding: 10px 15px;
    border-radius: 5px;
    font-size: 14px;
    cursor: pointer;
    display: none; /* Hidden by default */
    z-index: 1000;
}

.reset-tour-btn:hover {
    background-color: #e67e22;
}

.introjs-tooltip {
    border-radius: 12px; /* Rounded corners */
    box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.15); /* Soft shadow */
    font-size: 16px; /* Slightly larger font */
    padding: 15px; /* More breathing room */
    max-width: 350px; /* Prevents overly wide pop-ups */
}

.introjs-tooltip-title {
    font-weight: bold; /* Makes the title stand out */
    font-size: 18px;
}

.introjs-tooltiptext {
    line-height: 1.5; /* Improves readability */
    font-size: 15px;
}

.introjs-button {
    border-radius: 8px; /* Rounded buttons */
    padding: 8px 15px; /* Slightly bigger buttons */
    font-weight: bold;
    transition: all 0.3s ease-in-out; /* Smooth button effects */
}

.introjs-button:hover {
    opacity: 0.85; /* Subtle hover effect */
}

.introjs-prevbutton, .introjs-nextbutton {
    background-color: #007bff; /* Modern blue */
    color: white;
}

.introjs-prevbutton:hover, .introjs-nextbutton:hover {
    background-color: #0056b3; /* Darker hover effect */
}

.introjs-tooltipbuttons {
    display: flex;
    justify-content: space-between; /* Even spacing */
}

/* Style the progress dots */
.introjs-bullets ul li {
    background: #444 !important; /* Darker dots */
    opacity: 0.7;
}

.introjs-bullets ul li.active {
    background: #007bff !important; /* Blue active dot */
    opacity: 1;
}

.rounded-circle {
    border: 2px solid #ddd; /* Light border around the image */
    object-fit: cover;
}
@media (max-width: 576px) {
  .row > .col-md-3 {
    margin-bottom: 16px;
  }

  .row:last-child > .col-md-3:last-child {
    margin-bottom: 0; /* Optional: remove bottom margin on last card */
  }
}

.setup-modal {
  display: none;
  position: fixed;
  z-index: 1000;
  padding-top: 40px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.6);
}
.setup-modal-content {
  background-color: #fff;
  margin: auto;
  padding: 30px;
  border-radius: 10px;
  width: 90%;
  max-width: 600px;
  font-family: 'Segoe UI', sans-serif;
  box-shadow: 0 4px 12px rgba(0,0,0,0.3);
}
.setup-modal-content a {
  color: #007bff;
  text-decoration: none;
}
.setup-modal-content a:hover {
  text-decoration: underline;
}
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  cursor: pointer;
}
.close:hover {
  color: #000;
}

#programStepModal {
  z-index: 2000;
  display: none;
}

.go-to-program {
  color: white !important;
  text-decoration: none !important;
}

/* Smooth modal fade animation */
.modal.fade .modal-dialog {
  transition: transform 0.3s ease-out, opacity 0.3s ease-out;
  transform: translateY(-10px);
  opacity: 0;
}
.modal.fade.show .modal-dialog {
  transform: translateY(0);
  opacity: 1;
}

/* Reusable fade-in animation */
.fade-in {
  animation: fadeIn 0.35s ease-out forwards;
}
.fade-out {
  animation: fadeOut 0.35s ease-out forwards;
}

@keyframes fadeIn {
  from { opacity: 0; transform: scale(0.96); }
  to { opacity: 1; transform: scale(1); }
}
@keyframes fadeOut {
  from { opacity: 1; transform: scale(1); }
  to { opacity: 0; transform: scale(0.96); }
}

/* Leaderboard header */
.leaderboard-heading {
    font-size: 28px;
    font-weight: bold;
    background: linear-gradient(to right, #f12711, #f5af19);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-bottom: 20px;
}

/* Leaderboard column headers */
.table.leaderboard thead th {
    background-color: #f8f9fa;
    text-transform: uppercase;
    font-size: 13px;
    letter-spacing: 0.8px;
    color: #6c757d;
    border-bottom: 2px solid #dee2e6;
    position: sticky;
    top: 0;
    background-color: #fff;
    z-index: 2;
}

/* Hover effect for rows */
.table.leaderboard tbody tr:hover {
    background-color: #f2f2f2;
    transition: background-color 0.2s ease-in-out;
}

.table.leaderboard tbody tr:nth-child(-n+3) {
    position: relative;
    z-index: 1;
}


.table.leaderboard tbody tr:nth-child(-n+3)::before {
    content: "";
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    border: 2px solid;
    border-image: linear-gradient(45deg, #f12711, #f5af19) 1;
    border-radius: 8px;
    z-index: -1;
}

.table.leaderboard tbody tr:nth-child(-n+3):hover {
    box-shadow: 0 0 10px rgba(255, 191, 0, 0.4);
    transform: scale(1.01);
}


/* Leaderboard table */
.table.leaderboard {
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    margin-bottom: 30px;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(6px);
    -webkit-backdrop-filter: blur(6px);
}

/* Name column with emoji */
.table.leaderboard td:first-child {
    font-weight: bold;
    font-size: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}
/* Responsive fix for long names */
.table.leaderboard td {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* Add subtle borders between rows */
.table.leaderboard tbody td {
    border-top: 1px solid #e9ecef;
}

/* Highlight top rows */
.table.leaderboard tbody tr:nth-child(1) {
    background: linear-gradient(to right, #FFD700, #FFA500);
    color: black;
    font-size: 17px;
}
.table.leaderboard tbody tr:nth-child(2) {
    background: linear-gradient(to right, #C0C0C0, #DCDCDC);
}
.table.leaderboard tbody tr:nth-child(3) {
    background: linear-gradient(to right, #CD7F32, #deb887);
}

/* Add soft shadow on table hover */
.table.leaderboard:hover {
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

/* Smooth transition between pages (future AJAX) */
.leaderboard-transition {
    transition: opacity 0.3s ease-in-out;
}

/* Style the rank column (if you later add it) */
.table.leaderboard .rank-cell {
    font-weight: bold;
    font-size: 15px;
    color: #495057;
}

/* Add slight padding inside leaderboard cells */
.table.leaderboard td, .table.leaderboard th {
    padding: 10px 14px;
}

/* Responsive breakpoint (on mobile) */
@media (max-width: 768px) {
  .table.leaderboard td:first-child {
    font-size: 14px;
  }
  .table.leaderboard thead th {
    font-size: 12px;
  }
}

.feedback-msg {
  font-style: italic;
  color: #007bff;
  background: #eef6ff;
  border-left: 4px solid #007bff;
  padding: 8px 12px;
  border-radius: 5px;
}

html, body {
  height: 100%;
  min-height: 100vh;
  -webkit-overflow-scrolling: touch;
  overscroll-behavior: contain;
  touch-action: manipulation;
}

/* View Strategy Link — Mini Pill Style */
.view-strategy-link {
  font-size: 14px;
  font-weight: 500;
  color: #0a66c2; /* Professional LinkedIn blue */
  text-decoration: none;
  display: inline-block;
  margin-top: 4px;
  padding: 4px 10px; /* Slight padding to make it "pill" shaped */
  border-radius: 20px; /* Big rounding = pill effect */
  transition: all 0.3s ease;
  background-color: transparent;
}

/* Hover effect — subtle pill */
.view-strategy-link:hover {
  background-color: #e8f0fe;
  color: #004182;
  text-decoration: none;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05); /* 💎 subtle hover shadow */
}



/* Optional: if you want minor mobile tweaks separately later */
@media (max-width: 768px) {
  .view-strategy-link {
    font-size: 13px;
    padding: 3px 8px;
  }
}



.rank-immortal { color: #ff007f; font-weight: bold; }     /* pink glow */
.rank-ascended { color: #9400d3; font-weight: bold; }     /* dark violet */
.rank-emperor { color: #d4af37; font-weight: bold; }      /* gold */
.rank-titan { color: #708090; font-weight: bold; }        /* slate gray */
.rank-navigator { color: #00bfff; font-weight: bold; }    /* sky blue */
.rank-legend { color: #8b4513; font-weight: bold; }       /* bronze */
.rank-soarer { color: #4682b4; font-weight: bold; }       /* steel blue */
.rank-oracle { color: #9370db; font-weight: bold; }       /* medium purple */
.rank-sage { color: #3cb371; font-weight: bold; }         /* medium sea green */
.rank-wizard { color: #4b0082; font-weight: bold; }       /* indigo */
.rank-unicorn { color: #ff69b4; font-weight: bold; }      /* hot pink */
.rank-genius { color: #1e90ff; font-weight: bold; }       /* dodger blue */
.rank-explosive { color: #ff4500; font-weight: bold; }    /* orange red */
.rank-champion { color: #daa520; font-weight: bold; }     /* goldenrod */
.rank-diamond { color: #00ced1; font-weight: bold; }      /* dark turquoise */
.rank-rocket { color: #ff6347; font-weight: bold; }       /* tomato */
.rank-fire { color: #ff8c00; font-weight: bold; }         /* dark orange */
.rank-strong { color: #2e8b57; font-weight: bold; }       /* sea green */
.rank-star { color: #ffd700; font-weight: bold; }         /* yellow */
.rank-achiever { color: #7cfc00; font-weight: bold; }     /* lawn green */
.rank-sprout { color: #9acd32; font-weight: bold; }       /* yellow green */
.rank-hatchling { color: #ffdab9; font-weight: bold; }    /* peach puff */



@media (min-width: 992px) {
  .global-stats-card {
    margin-right: 1.5rem; /* Creates space between the stats card and signups on desktop */
  }
}


</style>



</head>
<body>
<button id="quickTourBtn" class="quick-tour-btn" onclick="startTour()">Take a Quick Tour</button>
<button id="hideTourBtn" class="hide-tour-btn" onclick="hideTourButton()">✖</button>




<!-- Floating Notification -->
<div id="copyNotification" class="copy-notification">
    <i class="fa fa-check-circle"></i> Copied to clipboard!
</div>


<?php include 'top-navbar.php'; ?>
    <!-- Sidebar Toggle Button (Mobile Only) -->
<button onclick="toggleSidebar()" class="sidebar-toggle-btn">
    <i class="fas fa-bars"></i>
</button>



<?php include 'sidebar.php'; ?>

<div class="sidebar-overlay" onclick="toggleSidebar()"></div>

        
        <div class="container-fluid p-4" style="max-width: 1400px; margin: 0 auto;">
            <h2>Dashboard <?php include 'google-translate-widget.php'; ?>
</h2>


<button id="installAppPrompt" style="display:none; margin-top:20px; padding:10px 20px; background-color:#007bff; color:#fff; border:none; border-radius:5px; font-size:16px;">
  Install <?= htmlspecialchars($brandName); ?> App
</button>

            
            <div id="account-policy-alert" class="alert alert-info" style="font-size: 14px; padding: 10px 15px; margin: 10px; border-radius: 5px; background-color: #e9f7fe; color: #0c5460; border: 1px solid #bee5eb;">
    ⚠️ Reminder: Free accounts must be setup within 14 days or they may be removed without warning.
    <a href="#" style="float: right; color: #0c5460; text-decoration: underline;" onclick="dismissPolicyAlert(event)">Dismiss</a>
</div>

<div id="fake-id-warning" class="alert alert-warning" style="font-size: 14px; padding: 10px 15px; margin: 10px; border-radius: 5px; background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba;">
    ⚠️ Please do not enter fake or invalid usernames into your setup steps. If you skip a program, your sponsor will still get the referral. Blocking this by using fake IDs is against system rules. Repeat offenders may be removed.
    <a href="#" style="float: right; color: #856404; text-decoration: underline;" onclick="dismissFakeIDWarning(event)">Dismiss</a>
</div>


<script>
  function dismissPolicyAlert(e) {
    e.preventDefault();
    document.getElementById('account-policy-alert').style.display = 'none';
    localStorage.setItem('hidePolicyAlert_v2', true);
  }

  if (localStorage.getItem('hidePolicyAlert_v2')) {
    document.getElementById('account-policy-alert').style.display = 'none';
  }
  
  function dismissFakeIDWarning(e) {
    e.preventDefault();
    document.getElementById('fake-id-warning').style.display = 'none';
    localStorage.setItem('hideFakeIDWarning', true);
}

if (localStorage.getItem('hideFakeIDWarning')) {
    document.getElementById('fake-id-warning').style.display = 'none';
}

</script>

            
<div class="card mb-4 shadow-sm" id="onboardingSteps" data-intro="Get Fully Setup and Ready to Earn – Start With These Steps." data-step="1">
  <div class="card-body d-flex flex-column flex-md-row align-items-start">
<div class="step-nav step-nav-wrapper p-2 me-md-4 flex-shrink-0 align-self-start">
<?php foreach ($steps as $index => $step): 
    $stepNumber = $index + 1;
    $isNew = isset($step['is_new']) && $step['is_new'] == 1;
    $icon = $step['icon_class'] ?: 'fa-circle';
    $label = $step['step_label'] ?? ("STEP {$stepNumber} – " . ($step['title'] ?? 'Complete This Step'));
    $modalId = 'stepModal' . $stepNumber;
?>

    <button class="step-btn <?= $index === 0 ? 'active' : '' ?>" data-step="<?= $stepNumber ?>">
        <i class="fas <?= htmlspecialchars($icon) ?> me-2"></i> STEP <?= $stepNumber ?><br>
        <small style="position: relative; display: inline-block;">
    <?= htmlspecialchars($label) ?>
    <?php if ($isNew): ?>
        <span style="
            background: linear-gradient(45deg, #ff6b6b, #f06595);
            color: white;
            font-weight: bold;
            font-size: 11px;
            padding: 2px 6px;
            border-radius: 6px;
            position: absolute;
            top: -8px;
            right: -45px;
            transform: rotate(-10deg);
            box-shadow: 0 0 8px rgba(255, 105, 135, 0.8); /* glow effect */
            animation: shakeNew 0.9s infinite ease-in-out;
        ">
            NEW
        </span>
        <style>
        @keyframes shakeNew {
            0%   { transform: rotate(-10deg) translateX(0); }
            20%  { transform: rotate(-10deg) translateX(2px); }
            40%  { transform: rotate(-10deg) translateX(-2px); }
            60%  { transform: rotate(-10deg) translateX(2px); }
            80%  { transform: rotate(-10deg) translateX(-1px); }
            100% { transform: rotate(-10deg) translateX(0); }
        }
        </style>
    <?php endif; ?>
</small>
    </button>
<?php endforeach; ?>


</div>



    <!-- Video Panel -->
    <div class="video-panel flex-grow-1">

<div class="video-wrapper ratio ratio-16x9 rounded shadow-sm border" style="max-height: 370px;">

  <iframe id="stepVideo" src="..." allowfullscreen></iframe>
</div>
<div id="stepCTAContainer" class="mt-3 text-center"></div> <!-- ⬅️ Moved OUTSIDE video box -->

<?php foreach ($steps as $index => $step): 
    $stepNumber = $index + 1;
    $icon = $step['icon_class'] ?: 'fa-circle';
    $label = $step['step_label'] ?: 'Complete This Step';
    $modalId = 'stepModal' . $stepNumber;
?>
    <div class="modal fade" id="<?= $modalId ?>" tabindex="-1" aria-labelledby="<?= $modalId ?>Label" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <?php
$overrideNotice = !empty($step['is_override']) ? ' <span class="badge bg-warning text-dark">Sponsor\'s Featured Step</span>' : '';
?>
<h5 class="modal-title" id="<?= $modalId ?>Label">
    Step <?= $stepNumber ?> - <?= htmlspecialchars($step['title']) ?><?= $overrideNotice ?>
</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <p><?= htmlspecialchars($step['subtitle']) ?></p>
            <div class="ratio ratio-16x9 mb-3">
                <iframe src="<?= htmlspecialchars($step['step_video_url']) ?>" allowfullscreen></iframe>
            </div>
            <form method="POST" action="save_program_id.php">
                <input type="hidden" name="slot_number" value="<?= $step['slot_number'] ?>">
                <input type="text" name="user_program_id" placeholder="<?= htmlspecialchars($step['placeholder_text']) ?>" class="form-control mb-3" required>
                <button class="btn btn-primary">Save This Step</button>
            </form>
          </div>
        </div>
      </div>
    </div>
<?php endforeach; ?>


    </div>
  </div>
</div>




 <div class="row">
    <div class="col-md-3">
        <div class="card text-white bg-primary">
            <div class="card-body">
                <h5>Total Signups</h5>
                <h4><?php echo $totalReferrals; ?></h4>
               
<a href="referrals.php" style="font-size: 12px; color: white; text-decoration: underline;">View Referrals</a>

            </div>
        </div>
    </div>

<div class="col-md-3">
    <div class="card text-white bg-success">
        <div class="card-body">
            <h5>Total Leads</h5>
            <h4><?php echo $totalLeads; ?></h4>
            <a href="my_leads.php" style="font-size: 12px; color: white; text-decoration: underline;">View Leads</a>
        </div>
    </div>
</div>

<?php
// Fetch the most recent click timestamp
$lastClickStmt = $pdo->prepare("SELECT created_at FROM clicks WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
$lastClickStmt->execute([$loggedInUserID]);
$lastClickTime = $lastClickStmt->fetchColumn();

function timeAgoCompact($datetime) {
    $timestamp = strtotime($datetime);
    $diff = time() - $timestamp;

    if ($diff < 60) return $diff . 's ago';
    if ($diff < 3600) return floor($diff / 60) . 'm ago';
    if ($diff < 86400) return floor($diff / 3600) . 'h ago';
    return 'Today ' . date('H:i', $timestamp); // fallback to time
}
?>

<div class="col-md-3">
    <div class="card text-white bg-warning">
        <div class="card-body">
            <h5>Total Clicks</h5>
            <h4><?php echo $totalClicks; ?></h4>
            <?php if ($lastClickTime): ?>
    <p style="font-size: 13px; margin-top: 8px; color: white;">
        Last Click: <?= timeAgoCompact($lastClickTime) ?>
    </p>
<?php endif; ?>

            <a href="clicks.php" style="font-size: 12px; color: white; text-decoration: underline;">View Clicks</a>
        </div>
    </div>
</div>


    <div class="col-md-3">
        <div class="card text-white bg-info">
            <div class="card-body">
                <h5>Latest Signups</h5>
<ul class="list-unstyled">
    <?php foreach ($latestSignups as $signup): 
        $fullName = trim(htmlspecialchars($signup['first_name'] . " " . $signup['last_name']));
        $emailHash = md5(strtolower(trim($signup['email'])));
        $gravatarURL = "https://www.gravatar.com/avatar/$emailHash?s=50&d=mp"; // 50px, default icon if no Gravatar
    ?>
        <li class="d-flex align-items-center mb-2">
            <img src="<?php echo $gravatarURL; ?>" alt="Profile" class="rounded-circle me-2" width="40" height="40">
            <span><?php echo $fullName; ?></span>
        </li>
    <?php endforeach; ?>
</ul>


            </div>
        </div>
    </div>
</div>

<div class="row">


<div class="my-4"></div>




<div class="col-md-8 mb-4">
  <div class="card shadow-sm">
    <div class="card-body">
      <h2 class="leaderboard-heading">🏆 Top Referrers</h2>
      <div id="leaderboard-container">
        <p>Loading leaderboard...</p>
      </div>
      <div class="text-center mt-3">
        <button id="prevPage" class="btn btn-outline-secondary me-2">⬅️ Previous</button>
        <button id="nextPage" class="btn btn-outline-secondary">Next ➡️</button>
      </div>
    </div>
  </div>
</div>

  <!-- Setup Progress Column (4/12 width) -->

  <div class="col-md-4 mb-4" style="margin-top: 3.2rem;">
    <div class="card shadow-sm border">
      <div class="card-body">
        <h5 class="card-title">📋 Setup Progress</h5>
        <p style="font-size: 13px; color: #555;">🕒 Accounts not fully setup within 14 days may be removed.</p>
        <ul class="list-unstyled mb-3">
        <?php
// ✅ Count sponsor programs clicked via cookies (max 10 for now)
$sponsorLinksClicked = 0;
for ($i = 0; $i < 10; $i++) {
    if (isset($_COOKIE["programClicked_$i"])) {
        $sponsorLinksClicked++;
    }
}
?>

          <li>Programs Joined: <?php echo $programsJoined . " / " . $totalPrograms; ?> <?php echo $programsJoined >= $totalPrograms ? '✅' : '❌'; ?></li>
          <li>Autoresponder Setup: <?php echo $autoresponderComplete ? '2 / 2 ✅' : '⚠️'; ?></li>
          <li>Own Programs Added: <?php echo $ownProgramsAdded . " / 5"; ?> <?php echo $ownProgramsAdded >= 5 ? '✅' : '📊'; ?></li>
          <li>Referral Link Created: <?php echo $referralLinkCreated ? '✅' : '❌'; ?></li>
          
         


        </ul>
        <button class="btn btn-primary" onclick="openSetupModal()">✅ Complete Setup Now</button>

        <!-- 🛡️ Status Badge -->
        <div class="text-center mt-4">
          <img src="images/badges/<?php echo $badgeFilename; ?>" alt="Status Badge" width="50" height="50" style="margin-bottom: 8px; opacity: 0.85; border: 1px solid #ddd; border-radius: 6px;">
          <div class="fw-semibold small text-<?php echo $isActive ? 'success' : 'danger'; ?>">
            <?php echo $badgeStatusText; ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</div> <!-- END .row -->


            
<div class="card mt-4">
    <div class="card-body" data-intro="Here is your referral link. If you don't see it, you need to set up a lead capture page and set a default page.">
        <h5 class="card-title">Your Referral Link</h5>
<?php if (!empty($referralLink)): ?>
<div class="card mt-4">
    <div class="card-body">
        <h5 class="card-title">Share Out Your Link:</h5>
        <input type="text" id="referral-link" class="form-control" value="<?php echo htmlspecialchars($referralLink); ?>" readonly>
        <button class="btn btn-primary mt-2" onclick="copyReferralLink()">
            <i class="fa fa-copy"></i> Copy Link
        </button> <?php if ($missingLeadsLeap): ?>
    <div class="alert alert-warning mt-3" role="alert">
        ⚠️ Your LeadsLeap integration is incomplete. <br>
        Please set up your <strong>LeadsLeap User ID</strong> and <strong>List Campaign ID</strong> 
        in the <a href="profile.php#leadsleap-form" target="_blank" class="alert-link">LeadsLeap Setup</a> page to activate your lead capture pages properly.
    </div>
<?php endif; ?>

    </div>
</div>
<?php else: ?>
<div class="alert alert-warning mt-4">
    No default lead capture page set. Please <a href="lead-capture.php"><strong>select one here</strong></a>.
</div>
<?php endif; ?>

    </div>
</div>

<?php if (!empty($referrerID)): ?>
    <div class="card mt-4">
        <div class="card-body" data-intro="This is your sponsor's info. You can reach out to them for support.">
            <h5 class="card-title">Your Sponsor</h5>
            <div class="d-flex align-items-center">
                <img src="<?php echo htmlspecialchars($sponsorProfileImage); ?>" alt="Sponsor Profile" class="rounded-circle me-2" width="50" height="50">
<div>
    <p><strong>Name:</strong> <?php echo $sponsorName; ?></p>
    <p><strong>Email:</strong> <a href="mailto:<?php echo $sponsorEmail; ?>"><?php echo $sponsorEmail; ?></a></p>

    <?php if (!empty($sponsorVideoURL)): ?>
        <button class="btn btn-sm btn-outline-primary mt-2" data-bs-toggle="modal" data-bs-target="#sponsorVideoModal">
            ▶️ Watch Welcome Video
        </button>
    <?php endif; ?>
</div>

            </div>
        </div>
    </div>
<?php endif; ?> <!-- ✅ Missing endif added here -->

<!-- ✅ NEW: Sponsor's Recommended Programs (Below "Your Sponsor" Card) -->
<?php if (!empty($sponsorPrograms)): ?>
    <div class="card mt-4">
        <div class="card-body" data-intro="Check out your sponsor's recommended income streams here.">
            <h5 class="card-title">🔥 Your Sponsor's Recommended Programs</h5>

            <div class="row">
<?php foreach ($sponsorPrograms as $program): ?>
    <?php
        $programName = isset($program['program_name']) ? $program['program_name'] : 'Untitled Program';
        $subHeadline = isset($program['sub_headline']) ? $program['sub_headline'] : '';
        $joinLink = isset($program['join_link']) ? $program['join_link'] : '#';
    ?>
    <div class="col-md-4 col-sm-6">
        <div class="card p-3 shadow-sm">
<?php
$programName = isset($program['program_name']) ? htmlspecialchars($program['program_name']) : null;
$subHeadline = isset($program['sub_headline']) ? htmlspecialchars($program['sub_headline']) : null;
?>

<h6 class="fw-bold"><?= $programName ?? '<span class="text-danger">Unnamed Program</span>' ?></h6>
<p class="text-muted mb-2"><?= $subHeadline ?? '<em>No description provided.</em>' ?></p>

<a href="<?= isset($program['join_link']) ? htmlspecialchars($program['join_link']) : '#'; ?>" target="_blank" class="btn btn-primary btn-sm">
    <i class="fa fa-sign-in-alt"></i> Join Program
</a>

        </div>
    </div>
<?php endforeach; ?>







                        </div>
                    </div>
           
            </div>

            <a href="settings.php" class="btn btn-secondary mt-3">
                <i class="fa fa-arrow-right"></i> View All Sponsor Programs
            </a>
        </div>
    </div>
<?php else: ?>  
    <p class="text-muted">Your sponsor has not added any programs yet.</p>
<?php endif; ?>


<!-- ✅ Close all necessary divs to maintain structure -->
</div> <!-- End of main container-fluid -->
</div> <!-- End of sidebar/main container -->

<?php include 'footer.php'; ?>


    
<script>
function copyReferralLink() {
    var copyText = document.getElementById("referral-link");
    navigator.clipboard.writeText(copyText.value).then(() => {
const notification = document.getElementById("copyNotification");
notification.classList.add("show");

setTimeout(() => {
    notification.classList.remove("show");
}, 2000);

    });
}
</script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    let tourButton = document.getElementById("quickTourBtn");
    let hideTourButton = document.getElementById("hideTourBtn");
    let restoreTourButton = document.getElementById("resetTourBtn");

    // Check if the tour was hidden
    if (localStorage.getItem("hideTour") === "true") {
        tourButton.style.display = "none";
        hideTourButton.style.display = "none";
        restoreTourButton.style.display = "block"; // Ensure Restore Tour is visible
    } else {
        tourButton.style.display = "block";
        hideTourButton.style.display = "block";
        restoreTourButton.style.display = "none"; // Ensure Restore Tour is hidden
    }
});

// Hide the tour button and show restore option
function hideTourButton() {
    document.getElementById("quickTourBtn").style.display = "none";
    document.getElementById("hideTourBtn").style.display = "none";
    document.getElementById("resetTourBtn").style.display = "block"; // Show restore link

    localStorage.setItem("hideTour", "true"); // Save state
}

// Restore the tour button when clicking "Restore Tour"
function resetTour() {
    localStorage.removeItem("hideTour");
    localStorage.removeItem("tourDismissed"); // 🧼 Reset dismissal too

    document.getElementById("quickTourBtn").style.display = "block";
    document.getElementById("hideTourBtn").style.display = "block";
    document.getElementById("resetTourBtn").style.display = "none";
}


// Start the tour when clicking the button
function startTour() {
    introJs().start();
}
</script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const tourDismissed = localStorage.getItem("tourDismissed");
    const tourHidden = localStorage.getItem("hideTour");

    // 🚫 If user has dismissed or hidden, don't launch
    if (tourDismissed || tourHidden === "true") return;

    // ⚙️ Setup instance
    const intro = introJs();

    // 🧠 Save dismissal on exit, completion, or beforeexit
    intro.onexit(() => localStorage.setItem("tourDismissed", "true"));
    intro.oncomplete(() => localStorage.setItem("tourDismissed", "true"));
    intro.onbeforeexit(() => localStorage.setItem("tourDismissed", "true"));

    // ✅ Now start the tour
    intro.start();
});
</script>




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


<script>
function toggleSidebar() {
  const sidebar = document.querySelector('.sidebar');
  const overlay = document.querySelector('.sidebar-overlay');
  const toggleBtn = document.querySelector('.sidebar-toggle-btn');

  sidebar.classList.toggle('open');
  overlay.classList.toggle('show');
  document.body.classList.toggle('sidebar-opened');

  // Hide toggle while sidebar is open
  if (document.body.classList.contains('sidebar-opened')) {
    toggleBtn.style.display = 'none';
  } else {
    // Check if top navbar is open — if so, don’t show the toggle yet
    const isNavOpen = document.querySelector('#navbarNav')?.classList.contains('show');
    toggleBtn.style.display = isNavOpen ? 'none' : 'block';
  }
}

// 🧠 Single listener to monitor the top navbar state
document.querySelector('.navbar-toggler')?.addEventListener('click', function () {
  const sidebarToggle = document.querySelector('.sidebar-toggle-btn');

  // Check after a short delay if navbar is open or not
  setTimeout(() => {
    const isNavOpen = document.querySelector('#navbarNav')?.classList.contains('show');

    // Force-close sidebar if open
    document.querySelector('.sidebar')?.classList.remove('open');
    document.querySelector('.sidebar-overlay')?.classList.remove('show');
    document.body.classList.remove('sidebar-opened');

    // Hide toggle while nav is open
    sidebarToggle.style.display = isNavOpen ? 'none' : 'block';
  }, 350); // Matches Bootstrap animation timing
});
</script>

<?php
// Fetch the programs array in PHP first
$stmt = $pdo->query("SELECT * FROM programs ORDER BY slot_number ASC LIMIT 4");
$programs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ✅ Check if referrer has Step 3 override
$step3Override = null;
if (!empty($referrerID)) {
    $stmt = $pdo->prepare("SELECT override_dashboard_step, override_program_slot, id FROM users WHERE user_id = ?");
    $stmt->execute([$referrerID]);
    $referrerData = $stmt->fetch(PDO::FETCH_ASSOC);

if ($referrerData && $referrerData['override_dashboard_step'] == 3 && $referrerData['override_program_slot']) {
    $slot = (int) $referrerData['override_program_slot']; // e.g. 1 = first program
    $referrerNumericId = $referrerData['id'];

    // Fetch all user_programs ordered by ID (ascending) for that sponsor
    $stmt = $pdo->prepare("SELECT * FROM user_programs WHERE user_id = ? ORDER BY id ASC");
    $stmt->execute([$referrerNumericId]);
    $allSponsorPrograms = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Simulate slot number (slot 1 = first program = index 0)
    $overrideProgram = $allSponsorPrograms[$slot - 1] ?? null;


        if ($overrideProgram) {
            $step3Override = [
                'slot' => 3,
                'title' => $overrideProgram['program_name'] ?? 'Featured Program',
                    'step_label' => $overrideProgram['program_name'] ?? 'Your Sponsor’s Program',
                'subtitle' => $overrideProgram['sub_headline'] ?? '',
                'step_video_url' => !empty($overrideProgram['youtube_link'])
    ? $overrideProgram['youtube_link']
    : 'https://www.youtube.com/embed/MdwyWJnxqgs',
                'modal_video_url' => '', // Optional future support
                'userID' => '', // Not editable
                'placeholder' => '',
                'finalURL' => $overrideProgram['join_link'] ?? '',
                'url_template' => '',
                'cta_text' => '🔥 Join This Program',
                'is_override' => true
            ];
        }
    }
}


$output = [];
foreach ($programs as $index => $prog) {
    $slot = $index + 1;

    // ✅ If slot 3 and override exists, insert override instead
    if ($slot == 3 && $step3Override) {
        $output[] = $step3Override;
        continue;
    }
echo "<!-- Available keys in \$prog: " . implode(', ', array_keys($prog)) . " -->";
echo "<!-- DEBUG PROGRAM {$index} -->";
echo "<!-- Full Row: " . print_r($prog, true) . " -->";

    $slot = $index + 1;

    // User’s saved value for this program (for the input box)
    $userInputValue = $userData["program_$slot"] ?? '';

    // Get sponsor’s value for this program slot
    $sponsorSlotValue = '';
    if (!empty($referrerID)) {
        $stmt = $pdo->prepare("SELECT program_$slot FROM users WHERE user_id = ?");
        $stmt->execute([$referrerID]);
        $sponsorSlotValue = $stmt->fetchColumn();
    }

    // Fallback to admin default
    $finalID = !empty($sponsorSlotValue) ? $sponsorSlotValue : ($prog['default_admin_referrer'] ?? '');
error_log("Program slot $slot → title: " . ($prog['program_name'] ?? 'NULL') . ", subtitle: " . ($prog['sub_headline'] ?? 'NULL'));

$finalURL = trim($prog['url_template']);
$isValidURL = filter_var(str_replace('{{USER_ID}}', $finalID, $finalURL), FILTER_VALIDATE_URL);

$output[] = [
    'slot' => $slot,
    'title' => isset($prog['title']) ? trim($prog['title']) : null,
    'subtitle' => isset($prog['subtitle']) ? trim($prog['subtitle']) : null,
    'step_video_url' => $prog['step_video_url'] ?? '',
    'modal_video_url' => $prog['video_url'] ?? '',
    'userID' => $userInputValue,
    'placeholder' => $prog['placeholder_text'] ?? '',
    'finalURL' => $isValidURL ? str_replace('{{USER_ID}}', $finalID, $finalURL) : '',
    'url_template' => $prog['url_template'] ?? '', // <- Add this line
    'cta_text' => $prog['cta_text'] ?? '',
];




}


?>

<script>
  const sponsorUser = <?php echo json_encode($userData, JSON_HEX_TAG); ?>;
</script>


<script>
const programs = <?php echo json_encode($output, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;


console.log("✅ sponsorUser is:", sponsorUser);

function closeProgramStepModal() {
  const modal = document.getElementById("programStepModal");
  modal.classList.remove("fade-in");
  modal.classList.add("fade-out");
  setTimeout(() => {
    modal.style.display = "none";
  }, 350);
}


function saveProgramID() {
  const slot = document.getElementById("userProgramInput").dataset.slot;
  const userID = document.getElementById("userProgramInput").value.trim();

  if (!userID) {
    alert("Please enter your ID.");
    return;
  }

  fetch("save_program_id.php", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: `slot=${encodeURIComponent(slot)}&program_id=${encodeURIComponent(userID)}`
  })
    .then(response => response.text())
    .then(data => {
alert(data);
programs[slot - 1].userID = userID; // ✅ Update the correct object
document.getElementById("userProgramInput").value = userID;
closeProgramStepModal();

    })
    .catch(error => {
      alert("Something went wrong while saving.");
      console.error("Save Error:", error);
    });
}

  
document.addEventListener("DOMContentLoaded", () => {
  // 👇 Modal Logic
function openProgramStepModal(program) {
  const isStaticStep = !program.url_template.includes("{{USER_ID}}"); // No input needed

  document.getElementById("programStepTitle").textContent =
    program.title && program.title.trim() !== "" ? program.title : `Step ${program.slot}`;
  
  document.getElementById("programStepSubtitle").textContent =
    program.subtitle && program.subtitle.trim() !== "" ? program.subtitle : "Click the button below to join this program.";
    
    // 👇 Add sponsor override badge if step 3 and is_override is true
const badgeContainer = document.getElementById("programStepBadgeContainer");
if (badgeContainer) {
  if (program.slot === 3 && program.is_override) {
    badgeContainer.innerHTML = `
      <span style="
        background: #ffd600;
        color: #000;
        padding: 4px 10px;
        border-radius: 50px;
        font-size: 13px;
        font-weight: 600;
        font-family: 'Barlow Condensed', sans-serif;
        display: inline-block;
        margin-bottom: 10px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.15);
      ">
        🔐 Your Sponsor Customized This Step
      </span>
    `;
  } else {
    badgeContainer.innerHTML = ""; // clear for non-step 3 or no override
  }
}

    
    const modalVideoContainer = document.getElementById("programModalVideoWrapper");
if (program.modal_video_url && program.modal_video_url.trim() !== "") {
  modalVideoContainer.innerHTML = `
    <div class="ratio ratio-16x9 mb-3">
      <iframe src="${program.modal_video_url}" allowfullscreen></iframe>
    </div>`;
} else {
  modalVideoContainer.innerHTML = ""; // Clear if no video
}


  const goBtn = document.getElementById("goToProgramBtn");

// ⛔ Hide button completely if there's no final URL
if (!program.finalURL || program.finalURL.trim() === "") {
  goBtn.style.display = "none";
} else {
  goBtn.style.display = "inline-block";
  goBtn.href = program.finalURL;
  goBtn.textContent = program.cta_text && program.cta_text.trim() !== ""
    ? program.cta_text
    : "🚀 LOCK IN YOUR SPOT!";
}

  // Set placeholder + value only if needed
  const input = document.getElementById("userProgramInput");
  input.placeholder = program.placeholder || "";
  input.value = program.userID || "";
  input.dataset.slot = program.slot;

  // Hide/show input + save button
  input.style.display = isStaticStep ? "none" : "block";
  document.querySelector("#programStepModal button.btn-primary").style.display = isStaticStep ? "none" : "inline-block";

  const modal = document.getElementById("programStepModal");
  modal.style.display = "block";
  modal.classList.remove("fade-out");
  modal.classList.add("fade-in");

  console.log("🧪 Program Data Received:", program);
}


  // 👇 Modal Close Outside Click
window.onclick = function(event) {
  const setupModal = document.getElementById("setupModal");
  const programModal = document.getElementById("programStepModal");

  if (event.target === setupModal) {
    closeSetupModal();
  }

  if (event.target === programModal) {
    closeProgramStepModal();
  }
};


  // 👇 Step Button Logic
  const buttons = document.querySelectorAll(".step-btn");
  const video = document.getElementById("stepVideo");
  const ctaContainer = document.getElementById("stepCTAContainer");

  buttons.forEach(btn => {
    btn.addEventListener("click", () => {
      const step = parseInt(btn.getAttribute("data-step"));

      // Update active class
      buttons.forEach(b => b.classList.remove("active"));
      btn.classList.add("active");

      // Load video
      if (programs[step - 1] && programs[step - 1].step_video_url) {
  video.src = programs[step - 1].step_video_url;
} else {
  video.src = ""; // fallback to blank or placeholder
}

// Load CTA Button
ctaContainer.innerHTML = "";
if (programs[step - 1]) {
  const prog = programs[step - 1];
  const ctaBtn = document.createElement("button");
  ctaBtn.style.cssText = `
  background: linear-gradient(to bottom, #F78C3E, #F24636);
  border: none;
  padding: 16px 22px;
  border-radius: 10px;
  color: white;
  font-weight: 800;
  font-family: 'Barlow Condensed', sans-serif;
  text-transform: uppercase;
  font-size: 18px;
  display: block;
  width: 100%;
  max-width: 580px;
  margin: 20px auto 0 auto;
  box-shadow: 0 5px 0 #B41A07;
  text-align: center;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
`;

  ctaBtn.textContent = `🚀 Complete Step ${step} NOW!`;
  ctaBtn.onclick = () => {
    console.log("✅ Green button clicked. Program:", prog);
    openProgramStepModal(prog);
  };
  ctaContainer.appendChild(ctaBtn);
}

    });
  });

  // Auto-trigger Step 1
  document.querySelector('.step-btn[data-step="1"]').click();
});

</script>



<!-- Setup Modal -->
<div id="setupModal" class="setup-modal">
  <div class="setup-modal-content">
    <span class="close" onclick="closeSetupModal()">&times;</span>
    <h2>🚀 Complete Your Setup</h2>

    <ol>
      <li>
        <strong>Programs Joined:</strong> Join all the core programs here.<br>
        <a href="settings.php" target="_blank">Go to Program Settings</a><br>
        <small>✅ Join all to maximize your commissions. Missing any = lost earnings!</small>
      </li>
      <hr>
      <li>
        <strong>Autoresponder Setup:</strong> Connect LeadsLeap to capture leads.<br>
        <a href="profile.php#leadsleap-form" target="_blank">Go to Profile Setup</a><br>
        <small>✅ LeadsLeap helps collect & manage your list. No setup = lost leads!</small>
      </li>
      <hr>
      <li>
        <strong>Own Programs Added:</strong> Add up to 5 extra programs.<br>
        <a href="user-programs.php" target="_blank">Go to Your Programs</a><br>
        <small>📊 Optional, but useful for showing your other tools.</small>
      </li>
      <hr>
      <li>
        <strong>Referral Link Created:</strong> Create a Lead Capture Page.<br>
        <a href="lead-capture.php" target="_blank">Create Your Link</a><br>
        <small>✅ Essential to start sharing & getting leads!</small>
      </li>
    </ol>

    <p style="margin-top: 15px; font-weight: bold;">Once you've completed all 4 steps, you're ready to go! 🚀</p>
  </div>
</div>
<script>
function openSetupModal() {
  const modal = document.getElementById("setupModal");
  modal.style.display = "block";
  modal.classList.remove("fade-out");
  modal.classList.add("fade-in");
}

function closeSetupModal() {
  const modal = document.getElementById("setupModal");
  modal.classList.remove("fade-in");
  modal.classList.add("fade-out");
  setTimeout(() => {
    modal.style.display = "none";
  }, 350); // Match animation duration
}

// Optional: close modal when clicking outside of it
window.onclick = function(event) {
  const setupModal = document.getElementById("setupModal");
  const programModal = document.getElementById("programStepModal");

  if (event.target === setupModal) {
    closeSetupModal();
  }

  if (event.target === programModal) {
    closeProgramStepModal();
  }
};

</script>

<!-- Program Step Modal -->
<div id="programStepModal" class="setup-modal">
  <div class="setup-modal-content">
    <span class="close" onclick="closeProgramStepModal()">&times;</span>
    <div id="programStepBadgeContainer" style="text-align: center;"></div>

    <h2 id="programStepTitle">NEW TITLE!</h2>
    <p id="programStepSubtitle">Step subtitle will go here TEST.</p>
    
    <!-- Inside #programStepModal content -->
<div id="programModalVideoWrapper" class="mt-3"></div>

    <div class="text-center mt-4">
<a id="goToProgramBtn" href="#" target="_blank" class="btn btn-danger btn-lg go-to-program">🚀 LOCK IN YOUR SPOT!</a>

</div>


    <input type="text" id="userProgramInput" class="form-control mt-2" placeholder="Enter your ID">
    <button onclick="saveProgramID()" class="btn btn-primary mt-3">💾 Save This Step</button>
    
  </div>
</div>

<div class="modal fade" id="sponsorVideoModal" tabindex="-1" aria-labelledby="sponsorVideoLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="sponsorVideoLabel">🎥 Meet Your Sponsor</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body text-center">
        <?php if (!empty($sponsorVideoURL)): ?>
          <div class="ratio ratio-16x9">
            <iframe src="<?= htmlspecialchars($sponsorVideoURL); ?>" allowfullscreen></iframe>
          </div>
        <?php else: ?>
          <p class="text-muted">Your sponsor hasn't added a welcome video yet.</p>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>


<script>
let currentPage = 1;

function loadLeaderboard(page = 1) {
  fetch(`leaderboard-data.php?page=${page}`)
    .then(res => res.json())
    .then(data => {
      const container = document.getElementById("leaderboard-container");
      if (data.length === 0) {
        container.innerHTML = "<p class='text-muted'>No more records to show.</p>";
        return;
      }

      let html = `
        <table class="table leaderboard table-striped table-bordered">
          <thead>
            <tr>
              <th>Name</th>
              <th>Referrals</th>
            </tr>
          </thead>
          <tbody>
      `;

data.forEach(user => {
  const fullName = `${user.first_name} ${user.last_name}`;
  const count = parseInt(user.referral_count);
  let badge = '';
  let badgeClass = '';
  let badgeTitle = '';

  if (count >= 1000) { badge = '🦸‍♂️'; badgeClass = 'rank-immortal'; badgeTitle = 'Immortal'; }
  else if (count >= 900) { badge = '🛸'; badgeClass = 'rank-ascended'; badgeTitle = 'Ascended'; }
  else if (count >= 800) { badge = '👑'; badgeClass = 'rank-emperor'; badgeTitle = 'Emperor'; }
  else if (count >= 700) { badge = '🗿'; badgeClass = 'rank-titan'; badgeTitle = 'Titan'; }
  else if (count >= 600) { badge = '🧭'; badgeClass = 'rank-navigator'; badgeTitle = 'Navigator'; }
  else if (count >= 500) { badge = '🏛️'; badgeClass = 'rank-legend'; badgeTitle = 'Legend'; }
  else if (count >= 400) { badge = '🦅'; badgeClass = 'rank-soarer'; badgeTitle = 'Soarer'; }
  else if (count >= 300) { badge = '🪐'; badgeClass = 'rank-oracle'; badgeTitle = 'Oracle'; }
  else if (count >= 200) { badge = '🧬'; badgeClass = 'rank-sage'; badgeTitle = 'Sage'; }
  else if (count >= 100) { badge = '🧙‍♂️'; badgeClass = 'rank-wizard'; badgeTitle = 'Wizard'; }
  else if (count >= 75) { badge = '🦄'; badgeClass = 'rank-unicorn'; badgeTitle = 'Unicorn'; }
  else if (count >= 50) { badge = '🧠'; badgeClass = 'rank-genius'; badgeTitle = 'Genius'; }
  else if (count >= 40) { badge = '🧨'; badgeClass = 'rank-explosive'; badgeTitle = 'Explosive'; }
  else if (count >= 30) { badge = '🏆'; badgeClass = 'rank-champion'; badgeTitle = 'Champion'; }
  else if (count >= 20) { badge = '💎'; badgeClass = 'rank-diamond'; badgeTitle = 'Diamond'; }
  else if (count >= 15) { badge = '🚀'; badgeClass = 'rank-rocket'; badgeTitle = 'Rocket'; }
  else if (count >= 10) { badge = '🔥'; badgeClass = 'rank-fire'; badgeTitle = 'Fire'; }
  else if (count >= 8) { badge = '💪'; badgeClass = 'rank-strong'; badgeTitle = 'Strong'; }
  else if (count >= 5) { badge = '🌟'; badgeClass = 'rank-star'; badgeTitle = 'Star'; }
  else if (count >= 3) { badge = '✅'; badgeClass = 'rank-achiever'; badgeTitle = 'Achiever'; }
  else if (count >= 2) { badge = '🌱'; badgeClass = 'rank-sprout'; badgeTitle = 'Sprout'; }
  else if (count >= 1) { badge = '🐣'; badgeClass = 'rank-hatchling'; badgeTitle = 'Hatchling'; }

  html += `
    <tr>
      <td>
        <div style="display: flex; flex-direction: column;">
          <span class="${badgeClass}" data-bs-toggle="tooltip" data-bs-placement="top" title="${badgeTitle}">${badge} ${fullName}</span>
          ${user.strategy_url ? `<a href="${user.strategy_url}" target="_blank" class="view-strategy-link">📄 View Strategy</a>` : ''}
        </div>
      </td>
      <td>${count}</td>
    </tr>
  `;
});


      html += "</tbody></table>";
      container.innerHTML = html;
      // ✅ Enable Bootstrap tooltips after loading new leaderboard content
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
tooltipTriggerList.forEach(el => new bootstrap.Tooltip(el));

    });
}

document.getElementById("prevPage").addEventListener("click", () => {
  if (currentPage > 1) {
    currentPage--;
    loadLeaderboard(currentPage);
  }
});

document.getElementById("nextPage").addEventListener("click", () => {
  currentPage++;
  loadLeaderboard(currentPage);
});

document.addEventListener("DOMContentLoaded", () => {
  loadLeaderboard();

  // ✅ Enable Bootstrap tooltips on initial load
  const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
  tooltipTriggerList.forEach(el => new bootstrap.Tooltip(el));
});
</script>




<script>
document.addEventListener('DOMContentLoaded', () => {
  const installBtn = document.getElementById('installAppPrompt');
  if (!installBtn) return;

  const isInStandaloneMode = ('standalone' in window.navigator) && window.navigator.standalone;
  const isiOS = /iphone|ipad|ipod/i.test(navigator.userAgent);
  const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  const alreadyInstalled = localStorage.getItem('mlmAppInstalled') === 'true';

  // ✅ FINAL DETECTION LOGIC
  if (isInStandaloneMode || alreadyInstalled) {
    installBtn.style.display = 'none';
    return;
  }

  // ✅ iOS Safari
  if (isiOS && isSafari) {
    installBtn.innerText = "📲 Add to Home Screen";
    installBtn.style.display = 'block';
    installBtn.onclick = () => {
      alert("To install:\n\n1. Tap the Share icon (box with arrow)\n2. Tap 'Add to Home Screen'");
      localStorage.setItem('mlmAppInstalled', 'true'); // 🧠 Remember next time
      installBtn.style.display = 'none';
    };
    return;
  }

  // ✅ Android Chrome
  window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    const deferredPrompt = e;

    installBtn.style.display = 'block';
    installBtn.onclick = () => {
      installBtn.style.display = 'none';
      deferredPrompt.prompt();
      deferredPrompt.userChoice.then((choiceResult) => {
        if (choiceResult.outcome === 'accepted') {
          localStorage.setItem('mlmAppInstalled', 'true');
        }
      });
    };
  });
});
</script>

<script>
if (window.navigator.standalone) {
  document.documentElement.style.height = '100%';
  document.body.style.height = '100%';
}
</script>

</body>
</html>
