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


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

$loggedInUser = $_SESSION['logged_in_user'];

// ✅ Fetch Branding Settings (Ensure your branding table has the logo)
$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

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

// ✅ Pagination Setup
$limit = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;

// ✅ Fetch Referrals
$sourceFilter = isset($_GET['source_filter']) ? trim($_GET['source_filter']) : '';

if (!empty($sourceFilter)) {
    $stmt = $pdo->prepare("SELECT user_id, first_name, last_name, email, tracking_source, created_at 
                           FROM users 
                           WHERE referrer_id = ? AND tracking_source = ?
                           ORDER BY created_at DESC 
                           LIMIT $limit OFFSET $offset");
    $stmt->execute([$loggedInUser, $sourceFilter]);
} else {
    $stmt = $pdo->prepare("SELECT user_id, first_name, last_name, email, tracking_source, created_at 
                           FROM users 
                           WHERE referrer_id = ?
                           ORDER BY created_at DESC 
                           LIMIT $limit OFFSET $offset");
    $stmt->execute([$loggedInUser]);
}

// ✅ Fetch grand total referrals count (unfiltered)
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE referrer_id = ?");
$stmt->execute([$loggedInUser]);
$grandTotalReferrals = $stmt->fetchColumn(); // ✅ Total count only

// ✅ Now fetch paginated referrals (moved down here to keep results fresh)
if (!empty($sourceFilter)) {
    $stmt = $pdo->prepare("SELECT user_id, first_name, last_name, email, tracking_source, created_at 
                           FROM users 
                           WHERE referrer_id = ? AND tracking_source = ?
                           ORDER BY created_at DESC 
                           LIMIT $limit OFFSET $offset");
    $stmt->execute([$loggedInUser, $sourceFilter]);
} else {
    $stmt = $pdo->prepare("SELECT user_id, first_name, last_name, email, tracking_source, created_at 
                           FROM users 
                           WHERE referrer_id = ?
                           ORDER BY created_at DESC 
                           LIMIT $limit OFFSET $offset");
    $stmt->execute([$loggedInUser]);
}
$referrals = $stmt->fetchAll(); // ✅ Now referrals list will be correct


// ✅ Count referrals by tracking source (not paginated, for summary)
if (!empty($sourceFilter)) {
    $stmt = $pdo->prepare("SELECT tracking_source, COUNT(*) as count 
                           FROM users 
                           WHERE referrer_id = ? AND tracking_source = ?
                           GROUP BY tracking_source");
    $stmt->execute([$loggedInUser, $sourceFilter]);
} else {
    $stmt = $pdo->prepare("SELECT tracking_source, COUNT(*) as count 
                           FROM users 
                           WHERE referrer_id = ?
                           GROUP BY tracking_source");
    $stmt->execute([$loggedInUser]);
}
$referralsBySource = $stmt->fetchAll(PDO::FETCH_ASSOC);


// ✅ Fetch Total Referral Count
if (!empty($sourceFilter)) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE referrer_id = ? AND tracking_source = ?");
    $stmt->execute([$loggedInUser, $sourceFilter]);
} else {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE referrer_id = ?");
    $stmt->execute([$loggedInUser]);
}
$totalReferrals = $stmt->fetchColumn();
$totalPages = max(1, ceil($totalReferrals / $limit));

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

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

function getUserAvatar($email) {
    $gravatarHash = md5(strtolower(trim($email)));
    $gravatarURL = "https://www.gravatar.com/avatar/$gravatarHash?s=40&d=404"; // `d=404` ensures a check without auto-fallback

    // Check if the Gravatar exists
    $headers = @get_headers($gravatarURL);
    if ($headers && strpos($headers[0], '200')) {
        return $gravatarURL; // Use Gravatar if available
    } else {
        return "assets/images/default-user-profile-image.png"; // Use local fallback
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Referrals</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; padding: 20px; }
        .sidebar { width: 250px; min-height: 100vh; background-color: #f8f9fa; padding: 20px; }
        .footer { background-color: #343a40; color: white; text-align: center; padding: 15px; margin-top: 20px; }
        .copy-notification { position: fixed; bottom: 20px; right: 20px; background: #28a745; color: white; padding: 10px 20px; border-radius: 8px; display: none; }
        
        .lead-summary ul {
    padding-left: 20px;
}
.lead-summary li {
    margin-bottom: 4px;
}

    </style>
</head>
<body>

<!-- ✅ Floating Copy 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>
 
    

    <!-- ✅ Main Content -->
    <div class="container-fluid">
        <h2>Your Referrals<?php include 'google-translate-widget.php'; ?>
</h2>
<a href="user-referred-activity.php" class="btn btn-outline-primary mb-3">
    View Referral Activity
</a>



        <?php if ($sponsor): ?>
            <h4 class="mt-4">Your Sponsor:</h4>
            <p><strong>Name:</strong> <?= htmlspecialchars($sponsor['first_name'] . ' ' . $sponsor['last_name']); ?></p>
            <p><strong>Email:</strong> <a href="mailto:<?= htmlspecialchars($sponsor['email']); ?>"><?= htmlspecialchars($sponsor['email']); ?></a></p>
        <?php endif; ?>

        <h4 class="mt-4">Your Direct Referrals</h4>
        
        <div class="lead-summary bg-light p-3 rounded border mb-3">
   <p><strong>Total Referrals:</strong> <?= $grandTotalReferrals; ?></p>

    <?php if (!empty($referralsBySource)): ?>
        <ul class="mb-0">
            <?php foreach ($referralsBySource as $row): ?>
                <li>
                    <strong><?= !empty($row['tracking_source']) ? htmlspecialchars($row['tracking_source']) : 'Unknown'; ?>:</strong>
                    <?= $row['count']; ?> signup<?= $row['count'] != 1 ? 's' : ''; ?>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php else: ?>
        <p>No referral sources found.</p>
    <?php endif; ?>
</div>

        
        <form method="GET" action="" class="mb-3">
    <label for="source_filter">Filter by Source:</label>
    <select name="source_filter" id="source_filter" class="form-select" style="max-width: 250px;" onchange="this.form.submit()">
        <option value="">All Sources</option>
        <?php
        $stmt = $pdo->prepare("SELECT DISTINCT tracking_source FROM users WHERE referrer_id = ? AND tracking_source IS NOT NULL");
        $stmt->execute([$loggedInUser]);
        $sources = $stmt->fetchAll(PDO::FETCH_COLUMN);

        foreach ($sources as $sourceOption):
            $selected = (isset($_GET['source_filter']) && $_GET['source_filter'] === $sourceOption) ? 'selected' : '';
            echo "<option value='" . htmlspecialchars($sourceOption) . "' $selected>" . htmlspecialchars($sourceOption) . "</option>";
        endforeach;
        ?>
    </select>
</form>

        <?php if (!empty($referrals)): ?>
        <input type="text" id="searchReferrals" class="form-control" placeholder="Search referrals...">
<div id="referralResults"></div>
<div class="table-responsive">
            <table class="table table-bordered mt-3" id="mainReferralTable">

                <thead>
                    <tr><th>Name</th><th>Username</th><th>Email</th><th>Tracking Source</th><th>Joined</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($referrals as $referral): ?>
<tr>
    <td>
        <img src="<?= getUserAvatar($referral['email'] ?? '') ?>" 
             alt="User Avatar" class="rounded-circle me-2" width="40" height="40">
        <?= htmlspecialchars(($referral['first_name'] ?? '') . " " . ($referral['last_name'] ?? '')); ?>
    </td>
    <td><?= htmlspecialchars($referral['user_id']); ?></td>
    <td><?= htmlspecialchars($referral['email'] ?? 'No email'); ?></td>
<td><?= htmlspecialchars($referral['tracking_source'] ?? 'Unknown'); ?></td>
<td><?= !empty($referral['created_at']) ? date('M j, Y', strtotime($referral['created_at'])) : ''; ?></td>
</tr>


                    <?php endforeach; ?>
                </tbody>
            </table>
</div>
            <!-- ✅ Pagination -->
<nav>
    <?php $queryString = !empty($sourceFilter) ? '&source_filter=' . urlencode($sourceFilter) : ''; ?>

    <ul class="pagination">
        <?php if ($page > 1): ?>
            <li class="page-item">
                <a class="page-link" href="?page=<?= $page - 1 . $queryString; ?>">Previous</a>
            </li>
        <?php endif; ?>

        <li class="page-item">
            <span class="page-link">Page <?= $page; ?> of <?= $totalPages; ?></span>
        </li>

        <?php if ($page < $totalPages): ?>
            <li class="page-item">
                <a class="page-link" href="?page=<?= $page + 1 . $queryString; ?>">Next</a>
            </li>
        <?php endif; ?>
    </ul>
</nav>

        <?php else: ?>
            <p>You have no referrals yet.</p>
        <?php endif; ?>

        <!-- ✅ Download Referrals CSV -->
<form action="download_referrals.php" method="POST">
    <input type="hidden" name="user_id" value="<?= htmlspecialchars($loggedInUser); ?>">
    <?php if (!empty($sourceFilter)): ?>
        <input type="hidden" name="source_filter" value="<?= htmlspecialchars($sourceFilter); ?>">
    <?php endif; ?>
    <button type="submit" class="btn btn-success">Download Referrals (CSV)</button>
</form>

    </div>
</div>

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

<script>
function copyReferralLink() {
    navigator.clipboard.writeText(document.getElementById("referralLink").value);
    document.getElementById("copyNotification").style.display = "block";
    setTimeout(() => document.getElementById("copyNotification").style.display = "none", 2000);
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>


<script>
document.getElementById("searchReferrals").addEventListener("keyup", function() {
    let query = this.value.trim();
    let resultsDiv = document.getElementById("referralResults");
    let mainTable = document.getElementById("mainReferralTable");
    let mainTableBody = mainTable.querySelector("tbody");

    if (query.length > 1) { 
        fetch("search-referrals.php?q=" + encodeURIComponent(query))
            .then(response => response.json())
            .then(data => {
                if (data.status === "success") {
let html = `<table class='table table-bordered'>
    <thead><tr><th>Name</th><th>Username</th><th>Email</th><th>Tracking Source</th><th>Joined</th></tr></thead>
    <tbody>`;

data.data.forEach(referral => {
    html += `<tr>
        <td>
            <img src='assets/images/default-user-profile-image.png'
                 class='rounded-circle me-2' width='40' height='40'>
            ${referral.first_name} ${referral.last_name}
        </td>
        <td>${referral.user_id}</td>
        <td>${referral.email}</td>
        <td>${referral.tracking_source ?? 'Unknown'}</td>
        <td>${referral.created_at ?? ''}</td>
    </tr>`;
});

                    html += `</tbody></table>`;

                    resultsDiv.innerHTML = html;
                    mainTable.style.display = "none"; // Hide original table
                } else if (data.status === "not_found") {
                    resultsDiv.innerHTML = "<p class='text-danger'>No referrals found.</p>";
                    mainTable.style.display = "table"; // Show original table
                }
            })
            .catch(error => console.error("Error fetching referrals:", error));
    } else {
        resultsDiv.innerHTML = ""; // Clear search results
        mainTable.style.display = "table"; // Restore main table
    }
});


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



</body>
</html>
