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

file_put_contents('debug_log.txt', "Script started\n", FILE_APPEND);

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

require_once 'db.php';


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

$loggedInUser = $_SESSION['logged_in_user'];

// ✅ Retrieve user data from the database
$stmt = $pdo->prepare("SELECT user_id, first_name, last_name, email, leadsleap_user_id, leadsleap_list_id, leadsleap_list_id_referrals, referrer_id, profile_video_url FROM users WHERE user_id = ?");

$stmt->execute([$loggedInUser]);
$userData = $stmt->fetch(PDO::FETCH_ASSOC);
$username = $userData['user_id'] ?? '';


if (!$userData) {
    die("<p style='color: red;'>❌ ERROR: No user found in the database with session ID ($loggedInUser)!</p>");
}

$referrerId = $userData['referrer_id'] ?? null;

// Fetch the referrer's LeadsLeap ID if a referrer exists
// Default LeadsLeap ID if sponsor does not have one
$defaultLeadsLeapId = $branding['default_leadsleap_id'] ?? 'keyte';
$defaultShareCodeLeads = $branding['share_code_leads'] ?? 'list-xxxxx';
$defaultShareCodeReferrals = $branding['share_code_referrals'] ?? 'list-yyyyy';

$referrerLeadsLeapId = $defaultLeadsLeapId; // Set default first

if ($referrerId) {
    $stmt = $pdo->prepare("SELECT leadsleap_user_id FROM users WHERE user_id = ?");
    $stmt->execute([$referrerId]);
    $referrerData = $stmt->fetch(PDO::FETCH_ASSOC);

    // Only override default if the sponsor has a valid LeadsLeap ID
    if (!empty($referrerData['leadsleap_user_id'])) {
        $referrerLeadsLeapId = $referrerData['leadsleap_user_id'];
    }
}


$user_id = $userData['user_id'];

// ✅ Process Profile Update Form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    
    $rawVideoURL = trim($_POST['profile_video_url'] ?? '');
$embedURL = '';

if (!empty($rawVideoURL)) {
    if (preg_match('/youtu\.be\/([^\?&]+)/', $rawVideoURL, $matches) ||
        preg_match('/v=([^\?&]+)/', $rawVideoURL, $matches) ||
        preg_match('/embed\/([^\?&]+)/', $rawVideoURL, $matches)) {
        $embedURL = "https://www.youtube.com/embed/" . $matches[1];
    } elseif (preg_match('/vimeo\.com\/(?:video\/)?([0-9]+)/', $rawVideoURL, $matches)) {
        $embedURL = "https://player.vimeo.com/video/" . $matches[1];
    } elseif (preg_match('/loom\.com\/share\/([a-zA-Z0-9]+)/', $rawVideoURL, $matches)) {
        $embedURL = "https://www.loom.com/embed/" . $matches[1];
    }
}


    if (empty($first_name) || empty($last_name) || empty($email)) {
        $errorMessage = "All fields except password are required.";
    } else {
        // ✅ Check if email is already taken by another user
        $stmt = $pdo->prepare("SELECT user_id FROM users WHERE email = ? AND user_id != ?");
        $stmt->execute([$email, $user_id]);
        if ($stmt->fetch()) {
            $errorMessage = "Email is already in use by another user.";
        } else {
            // ✅ Prepare update query
$updateColumns = ["first_name = ?", "last_name = ?", "email = ?", "profile_video_url = ?"];
$updateValues = [$first_name, $last_name, $email, $embedURL];


            // ✅ Hash new password if provided
            if (!empty($password)) {
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                $updateColumns[] = "edit_token = ?";
                $updateValues[] = $hashedPassword;
            }

            // ✅ Update user info in database
            $updateValues[] = $user_id;
            $stmt = $pdo->prepare("UPDATE users SET " . implode(", ", $updateColumns) . " WHERE user_id = ?");
            if ($stmt->execute($updateValues)) {
                // ✅ Redirect to avoid form resubmission on refresh
                header("Location: profile.php?profile_saved=1");
                exit;
            } else {
                $errorMessage = "Failed to update profile.";
            }
        }
    }
}

// ✅ Process LeadsLeap Update Form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_leadsleap'])) {
    $leadsleap_user_id = trim($_POST['leadsleap_user_id'] ?? '');
    $leadsleap_list_id = trim($_POST['leadsleap_list_id'] ?? '');
    $leadsleap_list_id_referrals = trim($_POST['leadsleap_list_id_referrals'] ?? ''); // ✅ New field for referrals


    if (!empty($leadsleap_user_id) && !empty($leadsleap_list_id)) {
        // ✅ Update the database
        $stmt = $pdo->prepare("UPDATE users SET leadsleap_user_id = ?, leadsleap_list_id = ?, leadsleap_list_id_referrals = ? WHERE user_id = ?");
        $result = $stmt->execute([$leadsleap_user_id, $leadsleap_list_id, $leadsleap_list_id_referrals, $user_id]);

        if ($result) {
            header("Location: profile.php?leadsleap_saved=1");
            exit;
        } else {
            $errorInfo = $stmt->errorInfo();
            file_put_contents('debug_log.txt', "DB Error: " . print_r($errorInfo, true) . "\n", FILE_APPEND);
            header("Location: profile.php?leadsleap_saved=0");
            exit;
        }
    } else {
        $errorMessage = "Both LeadsLeap User ID and List ID are required!";
    }
}

// ✅ Fetch Branding Settings
$stmt = $pdo->query("SELECT logo_image, default_leadsleap_id, share_code_leads, share_code_referrals, default_share_code FROM branding WHERE id = 1");
$branding = $stmt->fetch(PDO::FETCH_ASSOC);
$logoImage = $branding['logo_image'] ?? ''; // Default to empty if not set
$defaultLeadsLeapId = $branding['default_leadsleap_id'] ?? 'keyte';
$defaultShareCodeLeads = $branding['share_code_leads'] ?? 'list-xxxxx';
$defaultShareCodeReferrals = $branding['share_code_referrals'] ?? 'list-yyyyy';
$defaultShareCode = $branding['default_share_code'] ?? 'FALLBACK123';

// ✅ Generate Gravatar URL
$gravatarEmail = strtolower(trim($userData['email']));
$gravatarHash = md5($gravatarEmail);
$gravatarURL = "https://www.gravatar.com/avatar/$gravatarHash?s=150&d=mp"; // Default to 'mp' mystery person if no Gravatar exists

$errorMessage = "";
$successMessage = "";

?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile Settings</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">
    <link rel="stylesheet" href="assets/css/nav-style.css">

        <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: 20px;
    right: 20px;
    background-color: #28a745; /* Green (Success) */
    color: white;
    padding: 10px 20px;
    border-radius: 8px;
    font-size: 16px;
    display: none; /* Initially hidden */
    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;
    border: 3px solid #ddd;
    transition: 0.3s;
}
.rounded-circle:hover {
    border-color: #007bff;
}

.leadsleap-sharecodes {
    background-color: #f9f9f6; /* Soft creamy gray */
    border: 2px dashed #ccc;
    border-radius: 12px;
    padding: 20px;
    margin-top: 30px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
}

.leadsleap-sharecodes h4 {
    margin-bottom: 15px;
    font-weight: 600;
}

.leadsleap-sharecodes p {
    font-size: 15px;
    color: #555;
}

</style>


</head>
<body>

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


<?php include 'top-navbar.php'; ?>

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

<div class="sidebar-overlay" onclick="toggleSidebar()"></div>
        <div class="container-fluid p-4" style="background: #fff; min-height: 100vh;">
        <h2>Profile Settings<?php include 'google-translate-widget.php'; ?>
</h2>
        


        <?php if ($errorMessage): ?>
            <p class="text-danger"><?php echo htmlspecialchars($errorMessage); ?></p>
        <?php endif; ?>

 <?php if (isset($_GET['profile_saved']) && $_GET['profile_saved'] == 1): ?>
    <div class="alert alert-success"><i class="fa fa-check-circle"></i> Profile updated successfully!</div>
<?php elseif (!empty($errorMessage)): ?>
    <div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?= htmlspecialchars($errorMessage); ?></div>
<?php endif; ?>


    <div class="col-md-3 text-center">
        <img src="<?= htmlspecialchars($gravatarURL); ?>" alt="Profile Picture" class="rounded-circle border shadow" width="100" height="100">
        <p class="mt-2">
            <a href="https://gravatar.com/emails/" target="_blank" class="btn btn-outline-primary btn-sm">
                <i class="fa fa-pencil-alt"></i> Update Profile Picture
            </a>
        </p>
    </div>
        <form method="POST">
            <div class="mb-3">
                <label for="first_name" class="form-label">First Name</label>
                <input type="text" name="first_name" class="form-control" value="<?= htmlspecialchars($userData['first_name'] ?? ''); ?>" required>
            </div>

            <div class="mb-3">
                <label for="last_name" class="form-label">Last Name</label>
                <input type="text" name="last_name" class="form-control" value="<?= htmlspecialchars($userData['last_name'] ?? ''); ?>" required>
            </div>

            <div class="mb-3">
                <label for="email" class="form-label">Email</label>
                <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($userData['email'] ?? ''); ?>" required>
            </div>

            <div class="mb-3">
                <label for="password" class="form-label">New Password (Optional)</label>
                <input type="password" name="password" class="form-control" placeholder="Leave blank to keep current password">
            </div>
            
            <div class="mb-3">
<?php if (!empty($userData['profile_video_url']) && filter_var($userData['profile_video_url'], FILTER_VALIDATE_URL)): ?>
<div class="mb-3">
    <label class="form-label">Current Video Preview:</label>
    <div style="max-width: 360px;">
        <div class="ratio ratio-16x9 border rounded shadow-sm mb-2">
            <iframe src="<?= htmlspecialchars($userData['profile_video_url']) ?>" allowfullscreen></iframe>
        </div>
    </div>
</div>

<?php endif; ?>

<div class="mb-3">
    <label for="profile_video_url" class="form-label">Intro Video URL (Optional)</label>
    <input type="text" name="profile_video_url" class="form-control" 
        value="<?= htmlspecialchars($userData['profile_video_url'] ?? '') ?>"
        placeholder="https://youtu.be/xyz or loom.com/share/abc..." />
    <small class="text-muted">Paste a YouTube, Vimeo, or Loom video URL to show on your referrals' dashboard.</small>
</div>



            <button type="submit" name="update_profile" class="btn btn-primary">Save Changes</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>

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

  if (localStorage.getItem('hidePolicyAlert')) {
    document.getElementById('account-policy-alert').style.display = 'none';
  }
</script>


        </form>
        
        
        <hr> <!-- Adds a nice separation line -->
        
        <a id="leadsleap-form"></a>

<!-- ✅ LeadsLeap Integration -->

<?php if (!empty($referrerLeadsLeapId)): ?>
    <div class="alert alert-info">
        <strong>New to LeadsLeap?</strong> Join under your sponsor!  
<a href="https://leadsleap.com/?r=<?= htmlspecialchars($referrerLeadsLeapId); ?>" 
   class="btn btn-success btn-sm" 
   target="_blank" 
   rel="noopener noreferrer">
   <i class="fa fa-link"></i> Join LeadsLeap Now
</a>

    </div>
<?php endif; ?>


<h3>LeadsLeap Integration</h3>

<?php if (isset($_GET['leadsleap_saved']) && $_GET['leadsleap_saved'] == 1): ?>
    <div class="alert alert-success"><i class="fa fa-check-circle"></i> LeadsLeap settings saved successfully!</div>
<?php elseif (isset($_GET['leadsleap_saved']) && $_GET['leadsleap_saved'] == 0): ?>
    <div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> Failed to save LeadsLeap settings.</div>
<?php endif; ?>

<form action="profile.php" method="POST">
    <input type="hidden" name="update_leadsleap" value="1"> <!-- ✅ Identifies this form -->

    <label>LeadsLeap User ID</label>
    <input type="text" name="leadsleap_user_id" 
           value="<?= htmlspecialchars($userData['leadsleap_user_id'] ?? ''); ?>" 
           class="form-control">

    <label>LeadsLeap List Campaign ID (For Leads)</label>
    <input type="text" name="leadsleap_list_id" 
           value="<?= htmlspecialchars($userData['leadsleap_list_id'] ?? ''); ?>" 
           class="form-control">

    <label>LeadsLeap List Campaign ID (For Referrals)</label> <!-- ✅ NEW FIELD -->
<input type="text" name="leadsleap_list_id_referrals" 
       value="<?= htmlspecialchars($userData['leadsleap_list_id_referrals'] ?? ''); ?>" 
       class="form-control">


    <button type="submit" class="btn btn-primary mt-2">
        <i class="fa fa-save"></i> Save LeadsLeap Settings
    </button>
</form>

<!-- ✅ Done-For-You LeadsLeap Share Codes -->
<div class="mt-4 leadsleap-sharecodes">
    <h4>💡 Done-For-You LeadsLeap Share Codes</h4>
    <p>To help you get started faster, use the ready-made email follow-up series for both leads and referrals. Just copy the codes below and paste them into your LeadsLeap list settings.</p> 

    <div class="mb-3">
        <label class="form-label fw-bold" data-bs-toggle="tooltip" title="Use this share code in your LeadsLeap 'Follow-Up Series' list.">
    📧 Follow-Up for Leads (Capture Page Subscribers)
</label>

        <div class="input-group">
            <input type="text" id="shareCodeLeads" class="form-control" value="<?= htmlspecialchars($defaultShareCodeLeads); ?>" readonly>
            <button type="button" class="btn btn-outline-secondary" onclick="copyShareCode('shareCodeLeads')">
                <i class="fa fa-copy"></i> Copy
            </button>
        </div>
    </div>

    <div class="mb-3">
        <label class="form-label fw-bold" data-bs-toggle="tooltip" title="Use this one for the list where new registered members go.">
    👥 Follow-Up for Referrals (New Signups)
</label>

        <div class="input-group">
            <input type="text" id="shareCodeReferrals" class="form-control" value="<?= htmlspecialchars($defaultShareCodeReferrals); ?>" readonly>
            <button type="button" class="btn btn-outline-secondary" onclick="copyShareCode('shareCodeReferrals')">
                <i class="fa fa-copy"></i> Copy
            </button>
        </div>
        
        
        <!-- 🔗 Bridge Page URL Section -->
<div class="leadsleap-sharecodes mt-4">
    <h4>🔗 Your Bridge Page URL</h4>
    <p>Use this link when setting your redirect in LeadsLeap. It sends users to the system Bridge Page with your referral ID automatically included.</p>

    <div class="mb-2">
        <label class="form-label fw-bold" data-bs-toggle="tooltip" title="Use this as the destination URL in your email follow-ups.">
            🌉 Bridge Page Link
        </label>
        <div class="input-group">
            <?php
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
            $host = $_SERVER['HTTP_HOST'];
            $dir = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
            // Fetch the default_share_code from the branding table
$defaultShareCode = $branding['default_share_code'] ?? 'FALLBACK123';


$bridgeURL = "$protocol://$host$dir/bridge.php?code=" . urlencode($defaultShareCode) . "&ref=" . urlencode($username);
            ?>
            <input type="text" id="bridgePageUrl" 
                   class="form-control" 
                   value="<?= htmlspecialchars($bridgeURL); ?>" 
                   readonly>
            <button type="button" class="btn btn-outline-secondary" onclick="copyShareCode('bridgePageUrl')">
                <i class="fa fa-copy"></i> Copy
            </button>
        </div>
    </div>
</div>


        <!-- 🔥 Help Modal Trigger -->
<div class="text-end mt-3">
    <button type="button" class="btn btn-outline-info" data-bs-toggle="modal" data-bs-target="#helpModal">
        <i class="fa fa-question-circle"></i> Need Help?
    </button>
</div>



<!-- 💡 Help Modal -->
<div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="helpModalLabel"><i class="fa fa-book-open"></i> How to Set Up Your LeadsLeap Share Codes</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body text-center">
        <p class="fs-5 mb-4">Download our step-by-step PDF guide and get your autoresponder connected in minutes.</p>
        <a href="assets/pdf-help/leadleap-setup.pdf" target="_blank" class="btn btn-lg btn-success px-4 py-3">
          <i class="fa fa-download me-2"></i> Download Setup Guide (PDF)
        </a>
        <p class="mt-3 text-muted small">Opens in a new tab · No video required!</p>
      </div>
    </div>
  </div>
</div>

    </div>
</div>



        
 </div>

    </div>
</div>

<?php include 'footer.php'; ?>
<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');

  // Optional: toggle button visibility while sidebar is open
  if (document.body.classList.contains('sidebar-opened')) {
    toggleBtn.style.display = 'none';
  } else {
    toggleBtn.style.display = 'block';
  }
}

// ✅ Hide sidebar if top navbar is toggled (on mobile)
document.querySelector('.navbar-toggler')?.addEventListener('click', function () {
  document.querySelector('.sidebar')?.classList.remove('open');
  document.querySelector('.sidebar-overlay')?.classList.remove('show');
  document.body.classList.remove('sidebar-opened');
});
</script>


<script>
function copyShareCode(inputId) {
    const input = document.getElementById(inputId);
    input.select();
    input.setSelectionRange(0, 99999); // For mobile

    navigator.clipboard.writeText(input.value).then(function () {
        const notification = document.getElementById("copyNotification");
        notification.classList.add("show");
        setTimeout(() => notification.classList.remove("show"), 2000);
    });
}
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.forEach(function (tooltipTriggerEl) {
        new bootstrap.Tooltip(tooltipTriggerEl);
    });
});
</script>

</body>
</html>
