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

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

require_once 'db.php';


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

$loggedInUser = $_SESSION['logged_in_user'];

// Fetch user's existing lead capture pages
// ✅ Fetch the actual numeric user ID
$userQuery = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$userQuery->execute([$loggedInUser]);
$userData = $userQuery->fetch(PDO::FETCH_ASSOC);

if (!$userData) {
    die("Error: User not found.");
}

$user_id = $userData['id']; // The correct numeric ID

// ✅ Fetch the user's lead capture pages using the correct user_id
$stmt = $pdo->prepare("SELECT id, share_code, thumbnail, headline, created_at, default_capture FROM lead_capture_pages WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$leadCapturePages = $stmt->fetchAll(PDO::FETCH_ASSOC);


// ✅ Fetch Branding Settings (Ensure your branding table has the logo)
$stmt = $pdo->query("SELECT logo_image, brand_name FROM branding WHERE id = 1");
$branding = $stmt->fetch(PDO::FETCH_ASSOC);
$logoImage = $branding['logo_image'] ?? '';
$brandName = $branding['brand_name'] ?? 'Your Marketing System';
$defaultShareCode = $branding['default_share_code'] ?? 'F6716D';
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];
$directory = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$baseURL = $protocol . "://" . $host . $directory;

$userSaveClubLink = $baseURL . "/bridge.php?code=" . urlencode($defaultShareCode) . "&ref=" . urlencode($loggedInUser);



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

// ✅ Show success message if redirected from create-lead-capture.php
if (isset($_GET['success'])) {
    switch ($_GET['success']) {
        case '1':
            $successMessage = "Lead capture page created successfully!";
            break;
        case 'cloned':
            $successMessage = "Lead capture page duplicated successfully!";
            break;
    }
} elseif (isset($_GET['default_set']) && $_GET['default_set'] == 1) {
    $successMessage = "Default lead capture page updated successfully!";
}



// ✅ Fetch User Data (Now it exists)
$stmt = $pdo->prepare("SELECT first_name, last_name, email FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$userData = $stmt->fetch(PDO::FETCH_ASSOC) ?: ['first_name' => '', 'last_name' => '', 'email' => ''];

// ✅ Generate Gravatar URL based on user's email (Fix undefined index issue)
$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


// ✅ Handle Profile Update
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']);

    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, $loggedInUser]);
        if ($stmt->fetch()) {
            $errorMessage = "Email is already in use by another user.";
        } else {
            // ✅ Prepare update query
            $updateColumns = ["first_name = ?", "last_name = ?", "email = ?"];
            $updateValues = [$first_name, $last_name, $email];

            // ✅ 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[] = $loggedInUser;
            $stmt = $pdo->prepare("UPDATE users SET " . implode(", ", $updateColumns) . " WHERE user_id = ?");
            if ($stmt->execute($updateValues)) {
                $successMessage = "Profile updated successfully!";
                // Reload user data
                $stmt = $pdo->prepare("SELECT first_name, last_name, email FROM users WHERE user_id = ?");
                $stmt->execute([$loggedInUser]);
                $userData = $stmt->fetch(PDO::FETCH_ASSOC);
            } else {
                $errorMessage = "Failed to update profile.";
            }
        }
    }
}

?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lead Capture Pages</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;
}

  .card-img-top {
    object-fit: cover;
    height: 120px;
  }
  
   /* Adjust layout for mobile screens */
  @media (max-width: 576px) {
    .modal-header {
      flex-direction: column;
      align-items: flex-start;
    }

    .modal-title {
      width: 100%;
      margin-bottom: 10px;
    }

    .search-controls {
      width: 100%;
      display: flex;
      flex-direction: column;
    }

    .search-controls button,
    .search-controls input {
      width: 100%;
    }
  }
  
  .btn.float-end {
    margin-top: -38px;
    margin-right: 10px;
}

button.disabled[title]::after {
    content: attr(title);
    display: block;
    font-size: 0.8rem;
    color: #888;
    margin-top: 4px;
}


@keyframes bounceGlow {
  0%, 100% {
    transform: translateY(0);
    box-shadow: 0 0 10px #28a745, 0 0 20px #28a745;
  }
  50% {
    transform: translateY(-4px);
    box-shadow: 0 0 20px #28a745, 0 0 30px #28a745;
  }
}

.copy-glow {
  animation: bounceGlow 2s infinite;
}


</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>

<!-- Overlay for sidebar on mobile -->
    <div class="sidebar-overlay" onclick="toggleSidebar()"></div>

        <div class="container-fluid p-4" style="background: #fff; min-height: 100vh;">






        <h2>My Lead Capture Pages<?php include 'google-translate-widget.php'; ?>
</h2>

<div class="card mb-4 shadow-sm">
  <div class="card-body text-center">
<h5 class="card-title mb-3" style="font-weight: bold; color: #28a745;">
  🌟 Share Your <?= htmlspecialchars($brandName); ?> Link
</h5>


    <?php
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];
$directory = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$baseURL = $protocol . "://" . $host . $directory;

// ✅ Fetch the dynamic share code from branding table
$stmt = $pdo->query("SELECT default_share_code FROM branding WHERE id = 1");
$brandingRow = $stmt->fetch(PDO::FETCH_ASSOC);
$defaultShareCode = $brandingRow['default_share_code'] ?? '';

// ✅ Build the final Save Club referral link
$userSaveClubLink = $baseURL . "/bridge.php?code=" . urlencode($defaultShareCode) . "&ref=" . urlencode($loggedInUser);
?>

    <div class="input-group">
      <input type="text" class="form-control" id="saveClubLink" value="<?= htmlspecialchars($userSaveClubLink); ?>" readonly style="font-size: 16px;">
      <button class="btn btn-success copy-glow" type="button" onclick="copySaveClubLink()" title="Copy to Clipboard">
        <i class="fa fa-copy"></i>
      </button>
    </div>

    <small class="text-muted d-block mt-2">
  Click the icon to copy your personalized <?= htmlspecialchars($brandName); ?> link!
</small>
  </div>
</div>

<script>
function copySaveClubLink() {
  const copyText = document.getElementById('saveClubLink');
  copyText.select();
  copyText.setSelectionRange(0, 99999); // For mobile
  navigator.clipboard.writeText(copyText.value).then(() => {
    let notification = document.getElementById("copyNotification");
    notification.classList.add("show");
    setTimeout(() => { notification.classList.remove("show"); }, 2000);
  }).catch(err => console.error('Copy failed', err));
}
</script>

        <p>Create and manage your lead capture pages below.</p>
        
        <?php if (!empty($successMessage)) : ?>
    <div class="alert alert-success">
        <i class="fa fa-check-circle"></i> <?php echo $successMessage; ?>
    </div>
<?php endif; ?>

<?php
// ✅ Check if LeadsLeap integration is missing
$stmt = $pdo->prepare("SELECT leadsleap_user_id, leadsleap_list_id FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$leadsleapData = $stmt->fetch(PDO::FETCH_ASSOC);
$bridgeUnlocked = !empty($leadsleapData['leadsleap_user_id']) && !empty($leadsleapData['leadsleap_list_id']);
$missingLeadsLeap = empty($leadsleapData['leadsleap_user_id']) || empty($leadsleapData['leadsleap_list_id']);
?>

<!-- ✅ Responsive Button Wrapper -->
<div class="d-flex flex-wrap justify-content-center justify-content-md-between align-items-center gap-2 mb-3">

    <a href="create-lead-capture.php" class="btn btn-primary">
        <i class="fa fa-plus"></i> Create New Lead Capture Page
    </a>

<!-- Bridge Page Editor disabled -->


</div>


        




        <hr>

<!-- ✅ Always show the Share Code form -->
<form method="POST" action="use-share-code.php" class="mb-3">
    <label class="form-label">Use a Share Code:</label>
    <input type="text" name="share_code" class="form-control" required>
    <button type="submit" class="btn btn-primary mt-2">Use Share Code</button>

    <button type="button" class="btn btn-outline-success ms-2" id="openShareCodeLibrary">
        📚 ShareCode Library
    </button>
    <div id="shareCodeHint" class="share-code-hint" style="display: none;">✅ Share Code Added! Click "Use Share Code"</div>
</form>


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


<!-- ✅ Message for brand-new users -->
<?php if (empty($leadCapturePages)): ?>
    <p class="text-muted">You haven't created any lead capture pages yet.</p>
<?php else: ?>
    <!-- ✅ Continue with table of lead capture pages -->
    <div class="table-responsive">
        <table class="table table-striped">
            <!-- ... rest of your table output ... -->

<div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Thumbnail</th>  <!-- Add this for correct alignment -->
                        <th>Page Name</th>
                        <th>Share Code</th>  <!-- Add this for correct alignment -->
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
<tbody>
    <?php foreach ($leadCapturePages as $page): ?>
        <tr>
            <td>
   <img src="<?= !empty($page['thumbnail']) ? htmlspecialchars($page['thumbnail']) : 'assets/thumbnails/default.png'; ?>" 
    alt="Thumbnail" class="thumbnail-preview">

            </td>
            <td><?= htmlspecialchars($page['headline']); ?></td>
            <td>Share Code: <strong><?= htmlspecialchars($page['share_code'] ?? 'N/A'); ?></strong></td>

            <td><?= date('Y-m-d', strtotime($page['created_at'])); ?></td>
<td>
    <!-- Shareable Link Input -->
<?php
// ✅ Generate Dynamic Referral Link
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$dir = rtrim(dirname($_SERVER['PHP_SELF']), '/');
$baseURL = $protocol . "://" . $_SERVER['HTTP_HOST'] . $dir;
?>
<input type="text" class="form-control copy-link" 
       value="<?= $baseURL ?>/lead.php?code=<?= htmlspecialchars($page['share_code']); ?>&ref=<?= htmlspecialchars($loggedInUser); ?>" 
       id="leadCaptureUrl_<?= $page['id']; ?>" readonly>

<button class="btn btn-sm btn-primary copy-btn" onclick="copyToClipboard(this)">
    <i class="fa fa-copy"></i> Copy
</button>

<a href="<?= $baseURL ?>/lead.php?code=<?= htmlspecialchars($page['share_code']); ?>&ref=<?= htmlspecialchars($loggedInUser); ?>" 
   class="btn btn-info btn-sm" target="_blank">
    <i class="fa fa-eye"></i> Preview
</a>

<a href="edit-lead-capture.php?id=<?= $page['id']; ?>" class="btn btn-warning btn-sm">
    <i class="fa fa-edit"></i> Edit
</a>
<a href="duplicate-lead-capture.php?id=<?= $page['id']; ?>" class="btn btn-secondary btn-sm">
    <i class="fa fa-copy"></i> Duplicate
</a>


<a href="delete-lead-capture.php?id=<?= $page['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?');">
    <i class="fa fa-trash"></i> Delete
</a>

<form method="POST" action="set-default.php" style="display:inline;">
    <input type="hidden" name="page_id" value="<?= $page['id']; ?>">
    <button type="submit" class="btn btn-sm <?= ($page['default_capture'] == 1) ? 'btn-success' : 'btn-outline-success'; ?>">
        <?= ($page['default_capture'] == 1) ? 'Default' : 'Set as Default'; ?>
    </button>
</form>

<!-- ✅ NEW TRACKING LINK BUTTON -->
<button class="btn btn-secondary btn-sm" onclick="openTrackingModal('leadCaptureUrl_<?= $page['id']; ?>')">
    <i class="fa fa-link"></i> Tracking Link
</button>

</td>


        </tr>
    <?php endforeach; ?>
</tbody>

<style>
    .thumbnail-preview {
        width: 100px; /* Adjust as needed */
        height: auto;
        border-radius: 5px;
        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
    }
    
    <style>
  .highlight-added {
    border: 2px solid #28a745 !important;
    box-shadow: 0 0 5px #28a745;
    transition: all 0.3s ease-in-out;
  }

  .share-code-hint {
    color: #28a745;
    font-size: 0.9rem;
    margin-top: 5px;
    font-weight: 500;
    display: none;
  }
</style>

</style>



            </table>
        
        <?php endif; ?>
 </div>

        
 </div> <!-- ✅ Close Main Content Wrapper -->
</div> <!-- ✅ Close Flexbox -->

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

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

<script>
function copyToClipboard(button) {
    var input = button.previousElementSibling; // Get the input field next to the button
    navigator.clipboard.writeText(input.value).then(() => {
        let notification = document.getElementById("copyNotification");
        notification.classList.add("show"); // Show the notification
        setTimeout(() => { notification.classList.remove("show"); }, 2000); // Hide after 2 sec
    }).catch(err => console.error('Error copying text: ', err));
}
</script>

<!-- ✅ Tracking Link Pop-Up Modal -->
<div id="trackingModal" class="modal fade" tabindex="-1" aria-labelledby="trackingModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                <i class="fa fa-link"></i> Add Tracking to Your Link</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <label for="trackingInput" class="form-label">Enter Tracking Name (e.g., facebookad1):</label>
                <input type="text" id="trackingInput" class="form-control" placeholder="Enter tracking name..." oninput="updateTrackingUrl()">
                <p class="small text-muted mt-2">Your link will be updated automatically.</p>

                <!-- ✅ Live-updating preview -->
                <div class="mt-3">
                    <strong>Updated Link:</strong>
                    <input type="text" id="updatedTrackingUrl" class="form-control" readonly>
                </div>

                <!-- ✅ Tracking Added Message (Hidden Initially) -->
                <div id="trackingAddedMsg" class="alert alert-success mt-3" style="display: none;">
                    <i class="fa fa-check-circle"></i> Tracking Added!
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="applyTracking()">Apply</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<script>
let activeInputField = null; // Stores the current input field being updated

// ✅ Open the modal and store the active URL input field
function openTrackingModal(inputFieldId) {
    activeInputField = document.getElementById(inputFieldId); // Store the target field
    let currentUrl = activeInputField.value; // Get current URL
    document.getElementById('updatedTrackingUrl').value = currentUrl; // Set initial preview
    document.getElementById('trackingInput').value = ''; // Clear previous tracking input
    document.getElementById('trackingAddedMsg').style.display = 'none'; // Hide success message
    let trackingModal = new bootstrap.Modal(document.getElementById('trackingModal'));
    trackingModal.show(); // Show the modal
}

// ✅ Update the preview URL dynamically
function updateTrackingUrl() {
    let trackingValue = document.getElementById('trackingInput').value.trim(); // Get user input
    let baseUrl = activeInputField.value.split('&source=')[0]; // Remove existing tracking
    if (trackingValue) {
        baseUrl += `&source=${trackingValue}`; // Append tracking
    }
    let updatedUrlField = document.getElementById('updatedTrackingUrl');
    updatedUrlField.value = baseUrl; // Update preview

    // ✅ Auto-scroll to the end of the input
    setTimeout(() => {
        updatedUrlField.scrollLeft = updatedUrlField.scrollWidth; 
    }, 10);
}

// ✅ Apply tracking and update the main input field
function applyTracking() {
    let finalUrl = document.getElementById('updatedTrackingUrl').value; // Get final link
    activeInputField.value = finalUrl; // Update the main input field
    document.getElementById('trackingAddedMsg').style.display = 'block'; // Show success message
    setTimeout(() => { 
        document.getElementById('trackingAddedMsg').style.display = 'none'; 
    }, 2000); // Hide after 2 seconds
}
</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.addEventListener("DOMContentLoaded", function () {
  let allShareCodes = [];
  let filteredShareCodes = [];
  let currentPage = 1;
  const itemsPerPage = 8;

  document.getElementById("openShareCodeLibrary").addEventListener("click", () => {
    fetch('assets/data/share-codes.json')
      .then(response => response.json())
      .then(data => {
        allShareCodes = data;
        filteredShareCodes = [...allShareCodes];
        currentPage = 1;
        renderShareCodePage();
        new bootstrap.Modal(document.getElementById('shareCodeModal')).show();
      });
  });

  document.getElementById("toggleShareCodeSearch").addEventListener("click", () => {
    const input = document.getElementById("shareCodeSearchInput");
    input.classList.toggle("d-none");
    input.focus();
  });

  document.getElementById("shareCodeSearchInput").addEventListener("input", (e) => {
    const term = e.target.value.toLowerCase();
    filteredShareCodes = allShareCodes.filter(sc =>
      sc.title.toLowerCase().includes(term) ||
      sc.code.toLowerCase().includes(term) ||
      sc.thumb.toLowerCase().includes(term)
    );
    currentPage = 1;
    renderShareCodePage();
  });

  function renderShareCodePage() {
    const gallery = document.getElementById("shareCodeGallery");
    const pagination = document.getElementById("paginationControls");
    gallery.innerHTML = '';
    pagination.innerHTML = '';

    const start = (currentPage - 1) * itemsPerPage;
    const end = start + itemsPerPage;
    const currentItems = filteredShareCodes.slice(start, end);

    currentItems.forEach(sc => {
      const col = document.createElement("div");
      col.className = "col-md-3 mb-4";
      col.innerHTML = `
        <div class="card h-100 shadow-sm">
          <img src="${sc.thumb}" class="card-img-top" alt="${sc.title}">
          <div class="card-body p-2">
            <h6 class="card-title mb-2">${sc.title}</h6>
            <button class="btn btn-primary btn-sm w-100" onclick="useShareCode('${sc.code}')">Use This</button>
          </div>
        </div>`;
      gallery.appendChild(col);
    });

    const totalPages = Math.ceil(filteredShareCodes.length / itemsPerPage);
    for (let i = 1; i <= totalPages; i++) {
      const btn = document.createElement("button");
      btn.className = `btn btn-sm ${i === currentPage ? 'btn-primary' : 'btn-outline-primary'}`;
      btn.textContent = i;
      btn.addEventListener("click", () => {
        currentPage = i;
        renderShareCodePage();
      });
      pagination.appendChild(btn);
    }
  }

  window.useShareCode = function(code) {
    const input = document.querySelector('input[name="share_code"]');
    const hint = document.getElementById('shareCodeHint');

    input.value = code;
    input.classList.add("highlight-added");
    hint.style.display = "block";

    setTimeout(() => {
      input.classList.remove("highlight-added");
      hint.style.display = "none";
    }, 5000);

    bootstrap.Modal.getInstance(document.getElementById('shareCodeModal')).hide();
  };
});
</script>




<div id="shareCodeModal" class="modal fade" tabindex="-1" aria-labelledby="shareCodeModalLabel" 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="shareCodeModalLabel">ShareCode Library</h5>
        
        
<div class="search-controls mt-2">
  <button type="button" id="toggleShareCodeSearch" class="btn btn-sm btn-outline-secondary">
    🔎 Search
  </button>
  <input type="text" id="shareCodeSearchInput" class="form-control mt-2 d-none" placeholder="Type to search...">
</div>
<input type="text" id="shareCodeSearchInput" class="form-control mt-2 d-none" placeholder="Type to search...">


        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row text-center" id="shareCodeGallery">
          <!-- Thumbnails will be inserted here -->
        </div>
        <div id="paginationControls" class="d-flex justify-content-center mt-3 flex-wrap gap-2"></div>
      </div>
    </div>
  </div>
</div>

</body>
</html>
