<?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
// ✅ Fetch leads instead of referrals
$stmt = $pdo->prepare("SELECT name, email, source, created_at FROM leads WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$leads = $stmt->fetchAll();

$userData = $stmt->fetch(PDO::FETCH_ASSOC);

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



// ✅ Get the referrer from the session or URL
// ✅ CORRECT: Get the referrer from the URL, not from the logged-in user
$referrer = $loggedInUser;

if (!$referrer) {
    die("Error: No referrer found in the URL.");
}

// ✅ Fetch the Referrer’s User ID
$stmt = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$stmt->execute([$referrer]);
$referrerData = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$referrerData) {
    die("Error: Referrer not found in the database.");
}

$referrer_id = $referrerData['id']; // Store the correct user ID






// ✅ Correct: fetch signups where `referrer_id` matches the actual `user_id` (alphanumeric)
$stmt = $pdo->prepare("SELECT email FROM users WHERE referrer_id = ?");
$stmt->execute([$loggedInUser]);

$signedUpEmailsRaw = $stmt->fetchAll(PDO::FETCH_COLUMN);
$signedUpEmails = array_map('strtolower', array_map('trim', $signedUpEmailsRaw));

// ✅ Fetch all leads from this referrer (regardless of pagination) for accurate summary
$stmt = $pdo->prepare("SELECT email, source FROM leads WHERE user_id = ?");
$stmt->execute([$referrer_id]);
$allLeadsRaw = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ✅ Count total signups and match by source
$signedUpLeadCount = 0;
$signupCountsBySource = [];
$leadCountsBySource = [];

foreach ($allLeadsRaw as $lead) {
    $email = strtolower(trim($lead['email']));
    $source = strtolower(trim($lead['source'] ?? 'unknown'));

    // Count all leads per source
    if (!isset($leadCountsBySource[$source])) $leadCountsBySource[$source] = 0;
    $leadCountsBySource[$source]++;

    // Count signups per source
    if (in_array($email, $signedUpEmails)) {
        $signedUpLeadCount++;

        if (!isset($signupCountsBySource[$source])) $signupCountsBySource[$source] = 0;
        $signupCountsBySource[$source]++;
    }
}




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

// ✅ Modify query based on source filter
// ✅ Modify query based on source filter
if (!empty($source_filter)) {
    $stmt = $pdo->prepare("SELECT name, email, source, created_at FROM leads 
                           WHERE user_id = ? AND source = ?
                           ORDER BY created_at DESC 
                           LIMIT $limit OFFSET $offset");
    $stmt->execute([$referrer_id, $source_filter]);
} else {
    $stmt = $pdo->prepare("SELECT name, email, source, created_at FROM leads 
                           WHERE user_id = ? 
                           ORDER BY created_at DESC 
                           LIMIT $limit OFFSET $offset");
    $stmt->execute([$referrer_id]);
}


$leads = $stmt->fetchAll();



// ✅ Fetch distinct sources for the dropdown
$stmt = $pdo->prepare("SELECT DISTINCT source FROM leads WHERE user_id = ?");
$stmt->execute([$referrer_id]);
$sources = $stmt->fetchAll(PDO::FETCH_COLUMN);





// ✅ Fetch Total Leads Count
if (!empty($source_filter)) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM leads WHERE user_id = ? AND source = ?");
    $stmt->execute([$referrer_id, $source_filter]);
} else {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM leads WHERE user_id = ?");
    $stmt->execute([$referrer_id]);
}
$totalLeads = $stmt->fetchColumn();
$totalPages = max(1, ceil($totalLeads / $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);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Leads</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; }
        
        select.form-select {
    min-width: 200px; /* Ensures a minimum width */
    width: auto; /* Allows it to expand based on content */
    max-width: 100%; /* Prevents it from getting too large */
}

.lead-summary {
    background: #f1f1f1;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
}
.lead-summary ul {
    padding-left: 20px;
}
.lead-summary li {
    margin-bottom: 5px;
}

.table-success {
    background-color: #d4edda !important;
}

.btn-outline-primary:hover {
    box-shadow: 0 0 10px rgba(13, 110, 253, 0.5);
    transform: translateY(-1px);
}

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

        <?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; ?>
<form method="GET" action="">
    <label for="source_filter">Filter by Source:<?php include 'google-translate-widget.php'; ?>
</label>
    <select name="source_filter" id="source_filter" class="form-select" style="min-width: 200px; width: auto; max-width: 100%;" onchange="this.form.submit()">
        <option value="">All Sources</option>
<?php foreach ($sources as $source): ?>
    <?php if (!empty($source)): // ✅ Ignore NULL values ?>
        <option value="<?= htmlspecialchars($source, ENT_QUOTES, 'UTF-8') ?>" 
            <?= (isset($_GET['source_filter']) && $_GET['source_filter'] == $source) ? 'selected' : '' ?>>
            <?= htmlspecialchars($source, ENT_QUOTES, 'UTF-8') ?>
        </option>
    <?php endif; ?>
<?php endforeach; ?>

    </select>
</form>
<div class="lead-summary">
<h4 class="mt-4">Lead Summary</h4>
<div class="mb-4">
    <p><strong>Total Leads:</strong> <?= htmlspecialchars($totalLeads); ?></p>
    <?php
// Filtered signup count if source_filter is active
if (!empty($source_filter)) {
    $filteredSignupCount = 0;
    foreach ($leads as $lead) {
        $email = strtolower(trim($lead['email']));
        if (in_array($email, $signedUpEmails)) {
            $filteredSignupCount++;
        }
    }
    $label = !empty($source_filter) ? "Leads Who Signed Up (filtered)" : "Leads Who Signed Up";
echo "<p><strong>{$label}:</strong> " . (!empty($source_filter) ? $filteredSignupCount : $signedUpLeadCount) . " of {$totalLeads}</p>";
} else {
    echo "<p><strong>Leads Who Signed Up:</strong> {$signedUpLeadCount} of {$totalLeads}</p>";
}
?>

    <?php if (!empty($leadCountsBySource)): ?>
        <ul>
<?php foreach ($leadCountsBySource as $sourceKey => $sourceCount): ?>
    <?php
        $signupCount = $signupCountsBySource[$sourceKey] ?? 0;
        $conversionRate = $sourceCount > 0 ? round(($signupCount / $sourceCount) * 100) : 0;
    ?>
    <li>
        <strong><?= !empty($sourceKey) ? htmlspecialchars($sourceKey) : 'N/A'; ?>:</strong>
        <?= $sourceCount; ?> lead<?= $sourceCount != 1 ? 's' : ''; ?> | 
        <?= $signupCount; ?> signed up 
        (<?= $conversionRate; ?>%)
    </li>
<?php endforeach; ?>


        </ul>
    <?php else: ?>
        <p>No leads with source tracking yet.</p>
    <?php endif; ?>
</div>
</div>



        <h4 class="mt-4">Your Leads</h4>
        <?php if (!empty($leads)): ?>
       
<div class="table-responsive">
            <table class="table table-bordered mt-3">
                <thead>
<tr>
    <th>Name</th>
    <th>Email</th>
    <th>Source</th>
    <th>Date Collected</th>
    <th>Action</th>
</tr>

                </thead>
                <tbody>
<?php foreach ($leads as $lead): 
    $leadEmail = strtolower(trim($lead['email']));
    $isSignedUp = in_array($leadEmail, $signedUpEmails);
?>

<tr class="<?= $isSignedUp ? 'table-success' : ''; ?>">
    <td>
        <?= htmlspecialchars($lead['name']); ?>
        <?php if ($isSignedUp): ?>
            <span class="badge bg-success ms-2">Signed Up</span>
        <?php endif; ?>
    </td>
    <td><?= htmlspecialchars($lead['email']); ?></td>
    <td><?= !empty($lead['source']) ? htmlspecialchars($lead['source']) : "N/A"; ?></td>
    <td><?= htmlspecialchars($lead['created_at']); ?></td>
    <td><button class='delete-lead btn btn-danger' data-email='<?= htmlspecialchars($lead['email']); ?>'>❌ Delete</button></td>
</tr>
<?php endforeach; ?>


                </tbody>
            </table>
</div>
            <!-- ✅ Pagination -->
<?php
    // Build query string for filters
    $queryString = '';
    if (!empty($source_filter)) {
        $queryString = '&source_filter=' . urlencode($source_filter);
    }
?>
<nav>
    <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; ?>

<?php
$adjacents = 2; // Number of pages to show around current
$start = max(1, $page - $adjacents);
$end = min($totalPages, $page + $adjacents);

if ($start > 1) {
    echo '<li class="page-item"><a class="page-link" href="?page=1' . $queryString . '">1</a></li>';
    if ($start > 2) echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
}

for ($i = $start; $i <= $end; $i++) {
    echo '<li class="page-item ' . ($i == $page ? 'active' : '') . '">
            <a class="page-link" href="?page=' . $i . $queryString . '">' . $i . '</a>
          </li>';
}

if ($end < $totalPages) {
    if ($end < $totalPages - 1) echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
    echo '<li class="page-item"><a class="page-link" href="?page=' . $totalPages . $queryString . '">' . $totalPages . '</a></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_leads.php" method="POST">
    <input type="hidden" name="user_id" value="<?= htmlspecialchars($loggedInUser); ?>">
    <input type="hidden" name="source_filter" value="<?= isset($_GET['source_filter']) ? htmlspecialchars($_GET['source_filter']) : ''; ?>">
    <button type="submit" class="btn btn-success">Download Leads (CSV)</button>
</form>

    </div>
</div>

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

<script>
document.addEventListener("DOMContentLoaded", function() {
    document.querySelectorAll(".delete-lead").forEach(button => {
        button.addEventListener("click", function() {
            if (!confirm("Are you sure you want to delete this lead?")) return;

            let email = this.dataset.email;

            fetch("delete_lead.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ email })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.success);
                    this.closest("tr").remove(); // ✅ Remove row without reloading
                } else {
                    alert("Error: " + data.error);
                }
            })
            .catch(error => {
                alert("Request failed: " + error);
            });
        });
    });
});
</script>



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