<?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';


// ✅ Helper to convert video URL to embed version
function convertToEmbedURL($url) {
    if (preg_match('/youtu\.be\/([^\?\&]+)/', $url, $matches)) {
        return "https://www.youtube.com/embed/" . $matches[1];
    }
    if (preg_match('/youtube\.com.*[\/|v=]([^\&\?]+)/', $url, $matches)) {
        return "https://www.youtube.com/embed/" . $matches[1];
    }
    if (preg_match('/vimeo\.com\/(\d+)/', $url, $matches)) {
        return "https://player.vimeo.com/video/" . $matches[1];
    }
    if (preg_match('/loom\.com\/share\/([a-zA-Z0-9]+)/', $url, $matches)) {
        return "https://www.loom.com/embed/" . $matches[1];
    }
    return $url;
}


// ✅ 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 * FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$userData = $stmt->fetch(PDO::FETCH_ASSOC);

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

// ✅ Pagination setup
$videosPerPage = 8;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $videosPerPage;

// ✅ Get total count
$totalVideos = $pdo->query("SELECT COUNT(*) FROM video_training")->fetchColumn();
$totalPages = ceil($totalVideos / $videosPerPage);

// ✅ Get videos for current page
$stmt = $pdo->prepare("SELECT * FROM video_training ORDER BY created_at DESC LIMIT :limit OFFSET :offset");
$stmt->bindValue(':limit', $videosPerPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$videos = $stmt->fetchAll();



$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 = 'keyte';

$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 Bridge Page Customization Form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bridge_video_url'])) {
    $video_url_raw = trim($_POST['bridge_video_url'] ?? '');
    $video_url = convertToEmbedURL($video_url_raw);
    $cta_title = trim($_POST['bridge_cta_title'] ?? '');
    $cta_desc = trim($_POST['bridge_cta_description'] ?? '');
    $cta_btn_text = trim($_POST['bridge_cta_button_text'] ?? '');
    $cta_btn_link = trim($_POST['bridge_cta_button_link'] ?? '');
    $contact_link = trim($_POST['bridge_contact_link'] ?? '');

    $stmt = $pdo->prepare("UPDATE users SET 
        bridge_video_url = ?, 
        bridge_cta_title = ?, 
        bridge_cta_description = ?, 
        bridge_cta_button_text = ?, 
        bridge_cta_button_link = ?, 
        bridge_contact_link = ? 
        WHERE user_id = ?");
    $stmt->execute([
        $video_url, $cta_title, $cta_desc, $cta_btn_text, $cta_btn_link, $contact_link, $user_id
    ]);

    $success = true;

    // Refresh
    $stmt = $pdo->prepare("SELECT * FROM users WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $userData = $stmt->fetch(PDO::FETCH_ASSOC);
}

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 FROM branding WHERE id = 1");
$branding = $stmt->fetch(PDO::FETCH_ASSOC);
$logoImage = $branding['logo_image'] ?? ''; // Default to empty if not set

// ✅ 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>Customize Your Bridge Page!</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;
    margin: 0; /* No gap */
    padding: 0; /* No extra padding */
    font-family: Arial, sans-serif;
    background: #f7f7f7;
}




    /* 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;
}

      .training-grid {
  display: grid;
  gap: 1.5rem;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  max-width: 1000px;
  margin: 0 auto;
  justify-content: center;
    }

.training-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  display: flex;
  flex-direction: column;
}

    .training-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 22px rgba(0, 0, 0, 0.15);
    }

/* ✅ Maintain 16:9 aspect ratio */
.training-card .video-wrapper {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 */
  background-color: #000;
  overflow: hidden;
  border-bottom: none;

}

.training-card iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: none;
}

    .training-content {
      padding: 15px;
    }

    .training-title {
      font-size: 1.1rem;
      font-weight: 600;
      margin-bottom: 0.5rem;
      color: #222;
    }

    .training-description {
      font-size: 0.95rem;
      color: #555;
    }

    @media (max-width: 600px) {
      .training-card iframe {
        height: 160px;
      }
    }
    
    .pagination .page-item.active .page-link {
  background-color: #007bff;
  border-color: #007bff;
  color: white;
}

form label {
    font-weight: bold;
    display: block;
    margin: 15px 0 5px;
}

form input[type="text"],
form textarea {
    width: 100%;
    padding: 10px;
    font-size: 16px;
    margin-bottom: 12px;
    border: 1px solid #ccc;
    border-radius: 6px;
    background: white;
}

form textarea {
    resize: vertical;
    min-height: 100px;
}

form button.btn {
    background-color: #007bff;
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 16px;
    margin-top: 20px;
}

form button.btn:hover {
    background-color: #0056b3;
}

a.btn.preview-btn {
    display: inline-block;
    background-color: transparent;
    color: #333;
    padding: 12px 24px;
    border: 2px solid #ccc;
    border-radius: 6px;
    font-size: 16px;
    margin-top: 20px;
    text-decoration: none;
    vertical-align: middle;
    transition: all 0.2s ease-in-out;
}

a.btn.preview-btn:hover {
    background-color: #f8f8f8;
    border-color: #999;
}

.video-tutorial-wrapper {
    max-width: 800px;
    margin: 30px auto 40px;
    text-align: center;
}

.video-container {
    position: relative;
    padding-top: 56.25%; /* 16:9 Aspect Ratio */
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 8px 18px rgba(0, 0, 0, 0.1);
    border: 1px solid #ddd;
    background: #000;
}

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

.video-caption {
    margin-top: 12px;
    font-size: 16px;
    color: #555;
}

.input-group input,
.input-group .btn {
    height: 42px !important;      /* exact match */
    padding: 0 1rem;
    font-size: 16px;
    line-height: 1.5;
    border-radius: 6px;
}

.input-group .btn {
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
}


</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;">
   <h1><i class="fa-solid fa-gear"></i> Customize Your Bridge Page<?php include 'google-translate-widget.php'; ?>
</h1>

<div class="video-tutorial-wrapper">
    <div class="video-container">
        <iframe 
            src="https://www.youtube.com/embed/rXfCu7UneYo" 
            frameborder="0" 
            allowfullscreen
        ></iframe>
    </div>
    <p class="video-caption">👆 Watch this quick tutorial before editing your Bridge Page settings!</p>
</div>


  <?php if (!empty($success)): ?>
    <div class="success">Your settings have been saved.</div>
<?php endif; ?>

<?php
// Load lead magnet templates
$templateFile = __DIR__ . '/rb/data/templates.json';
$templates = json_decode(file_get_contents($templateFile), true);
?>

<div class="mb-3">
    <label for="lead_magnet_select"><strong>📘 Choose a Lead Magnet (optional):</strong></label>
    <select id="lead_magnet_select" class="form-select">
        <option value="">-- Select a Lead Magnet --</option>
        <?php foreach ($templates as $key => $item): ?>
<option value="<?= htmlspecialchars($key) ?>"
        data-headline="<?= htmlspecialchars($item['headline']) ?>"
        data-subheadline="<?= htmlspecialchars($item['subheadline']) ?>"
        data-image="<?= htmlspecialchars($item['image']) ?>">
    <?= htmlspecialchars($item['headline']) ?>
</option>

        <?php endforeach; ?>
    </select>
    
    <div id="lead_magnet_preview" style="margin-top: 10px; display: none; text-align: center;">
    <img id="lead_magnet_image" src="" alt="Lead Magnet Preview"
         style="max-width: 300px; height: auto; border-radius: 12px; box-shadow: 0 4px 10px rgba(0,0,0,0.15);">
</div>

</div>


<form method="post">
    <div class="mb-3">
        <label for="bridge_video_url">Custom Video URL (YouTube, Vimeo, Loom) - OPTIONAL</label>
        <input type="text" name="bridge_video_url" id="bridge_video_url" class="form-control" value="<?= htmlspecialchars($userData['bridge_video_url'] ?? '') ?>">
    </div>

    <div class="mb-3">
        <label for="bridge_cta_title">CTA Title</label>
        <input type="text" name="bridge_cta_title" id="bridge_cta_title" class="form-control" value="<?= htmlspecialchars($userData['bridge_cta_title'] ?? '') ?>">
    </div>

    <div class="mb-3">
        <label for="bridge_cta_description">CTA Description - OPTIONAL</label>
        <textarea name="bridge_cta_description" id="bridge_cta_description" class="form-control"><?= htmlspecialchars($userData['bridge_cta_description'] ?? '') ?></textarea>
    </div>

    <div class="mb-3">
        <label for="bridge_cta_button_text">CTA Button Text</label>
        <input type="text" name="bridge_cta_button_text" id="bridge_cta_button_text" class="form-control" value="<?= htmlspecialchars($userData['bridge_cta_button_text'] ?? '') ?>">
    </div>

    <div class="mb-3">
        <label for="bridge_cta_button_link">CTA Button Link</label>
        <div class="input-group">
    <input type="text" name="bridge_cta_button_link" id="bridge_cta_button_link" class="form-control" value="<?= htmlspecialchars($userData['bridge_cta_button_link'] ?? '') ?>">
    <button type="button" class="btn btn-outline-secondary" style="margin-top: 1px;" onclick="previewLink()">🔍 Preview</button>
</div>
    </div>

    <div class="mb-3">
        <label for="bridge_contact_link">Contact Link (email or URL)</label>
        <input type="text" name="bridge_contact_link" id="bridge_contact_link" class="form-control" value="<?= htmlspecialchars($userData['bridge_contact_link'] ?: $userData['email']) ?>">
    </div>

    <div class="d-flex gap-3 mt-3">
    <button type="submit" class="btn btn-primary">
        💾 Save Settings
    </button>
    <a href="bridge.php?code=F6716D&ref=<?= urlencode($loggedInUser); ?>"
       target="_blank"
       class="btn preview-btn">
       🔍 Preview Page
    </a>
</div>
</form>



</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>
document.getElementById('lead_magnet_select')?.addEventListener('change', function () {
    const selected = this.options[this.selectedIndex];
    const headline = selected.getAttribute('data-headline');
    const subheadline = selected.getAttribute('data-subheadline');
    const image = selected.getAttribute('data-image');
    const category = this.value;

    const firstName = <?= json_encode($userData['first_name'] ?? ''); ?>;
    const lastName = <?= json_encode($userData['last_name'] ?? ''); ?>;
    const fullName = `${firstName} ${lastName}`.trim();
    const userId = <?= json_encode($userData['user_id'] ?? ''); ?>;
    const L = "CFFC65";

    if (headline && subheadline && category) {
        document.getElementById('bridge_cta_title').value = headline;
        document.getElementById('bridge_cta_description').value = subheadline;
        document.getElementById('bridge_cta_button_text').value = "DOWNLOAD YOUR PDF NOW!";
        document.getElementById('bridge_cta_button_link').value =
            `https://rebrandxpress.com/txc/rb/download.php?L=${L}&name=${encodeURIComponent(fullName)}&ref_id=${userId}&category=${category}&b=0`;

        // ✅ Show image preview
        if (image) {
            const previewDiv = document.getElementById('lead_magnet_preview');
            const previewImg = document.getElementById('lead_magnet_image');
            previewImg.src = `rb/assets/graphics/${image}`;
            previewDiv.style.display = 'block';
        }
    } else {
        document.getElementById('lead_magnet_preview').style.display = 'none';
    }
});

function previewLink() {
    const link = document.getElementById('bridge_cta_button_link').value.trim();
    if (link) {
        window.open(link, '_blank');
    } else {
        alert("Please generate or enter a link first.");
    }
}

</script>




</body>
</html>
