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




$inactiveDays = isset($_GET['inactive_days']) ? (int)$_GET['inactive_days'] : 0;


$filter = $_GET['status'] ?? '';



$filters = ["u.referrer_id = ?"]; // always required

if ($filter === 'active') {
    $filters[] = "a.leadsleap_id_set = 1 AND a.leadsleap_lists_set = 1 AND a.program_ids_set = 1";
} elseif ($filter === 'inactive') {
    $filters[] = "(a.leadsleap_id_set = 0 OR a.leadsleap_lists_set = 0 OR a.program_ids_set = 0)";
}

// ✅ Apply last_login cutoff regardless of status
if ($inactiveDays > 0) {
    $cutoffDate = date('Y-m-d H:i:s', strtotime("-$inactiveDays days"));
    $filters[] = "a.last_login < '$cutoffDate'";
}


$search = $_GET['search'] ?? '';
if (!empty($search)) {
    $filters[] = "(u.email LIKE ? OR u.user_id LIKE ?)";
}







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

$loggedInUser = $_SESSION['logged_in_user'];

// ✅ Get list of sources for dropdown
$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);

// ✅ Read selected source from query
$selectedSource = $_GET['source_filter'] ?? '';
if (!empty($selectedSource)) {
    $filters[] = "u.tracking_source = ?";
}

$whereClause = implode(" AND ", $filters);



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

// ✅ Get total count
$stmtCount = $pdo->prepare("
    SELECT COUNT(*) 
    FROM user_activity a 
    JOIN users u ON a.user_id = u.user_id 
    WHERE $whereClause
");
$params = [];
$params[] = $loggedInUser;

if (!empty($filter) && $filter === 'active') {
    // no extra params
} elseif (!empty($filter) && $filter === 'inactive') {
    // no extra params
}

if ($inactiveDays > 0) {
    // no extra params (cutoff is hardcoded into WHERE string)
}

if (!empty($search)) {
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($selectedSource)) {
    $params[] = $selectedSource;
}



$stmtCount->execute($params);
$totalRows = $stmtCount->fetchColumn();
$totalPages = max(1, ceil($totalRows / $limit));

// ✅ Fetch activity rows
$sortDirection = ($_GET['sort'] ?? '') === 'inactive' ? 'ASC' : 'DESC';

$stmt = $pdo->prepare("
    SELECT a.*, u.email, u.first_name, u.tracking_source
    FROM user_activity a 
    JOIN users u ON a.user_id = u.user_id 
    WHERE $whereClause
    ORDER BY a.last_login $sortDirection
    LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ✅ Branding for header logo
$stmt = $pdo->query("SELECT logo_image FROM branding WHERE id = 1");
$branding = $stmt->fetch(PDO::FETCH_ASSOC);
$logoImage = $branding['logo_image'] ?? '';


// Count all referrals by status
function getReferralCount($pdo, $loggedInUser, $extraCondition = '') {
    $stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM user_activity a
        JOIN users u ON a.user_id = u.user_id
        WHERE u.referrer_id = ? $extraCondition
    ");
    $stmt->execute([$loggedInUser]);
    return $stmt->fetchColumn();
}

$countAll = getReferralCount($pdo, $loggedInUser);
$countActive = getReferralCount($pdo, $loggedInUser, "AND a.leadsleap_id_set = 1 AND a.leadsleap_lists_set = 1 AND a.program_ids_set = 1");
$countInactive = getReferralCount($pdo, $loggedInUser, "AND (a.leadsleap_id_set = 0 OR a.leadsleap_lists_set = 0 OR a.program_ids_set = 0)");



?>

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

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

        
       <h3>📊 User Activity Overview<?php include 'google-translate-widget.php'; ?>
</h3>
       
       <div class="lead-summary mb-3">
    <strong>Summary:</strong>
    <ul>
        <li>Total Referrals: <?= $totalRows ?></li>
        <li>
    Showing:
    <?php
        if ($filter === 'active') {
            echo "Active";
        } elseif ($filter === 'inactive') {
            echo "Inactive";
        } else {
            echo "All";
        }

        if ($inactiveDays > 0) {
            echo " (users who haven't logged in for $inactiveDays days)";
        }
    ?>
</li>
    </ul>
</div>

<div class="mb-3">
    <strong>Legend:</strong>
    <span class="ms-2">✅ Fully Set</span>
    <span class="ms-2">⚠️ Partially Set (Only 1 List Campaign Added)</span>
    <span class="ms-2">❌ Not Set</span>
</div>

    <div class="mb-3">
<?php
$currentParams = $_GET;
?>

<div class="mb-3">
    <strong>Status Filters:</strong>
    <?php
    foreach (['' => 'All', 'active' => 'Active', 'inactive' => 'Inactive'] as $statusValue => $label) {
        $params = $currentParams;
        $params['status'] = $statusValue;
        $query = http_build_query($params);

        $btnClass = match ($statusValue) {
            '' => 'btn-secondary',
            'active' => 'btn-success',
            'inactive' => 'btn-danger',
        };

        $count = match ($statusValue) {
            '' => $countAll,
            'active' => $countActive,
            'inactive' => $countInactive,
        };

        echo "<a href=\"?$query\" class=\"btn $btnClass filter-btn me-1\">$label ($count)</a>";
    }
    ?>
</div>

    </div>


    
<form method="GET" class="mb-3">

    <label for="source_filter">Filter by Source:</label>
<select name="source_filter" class="form-select d-inline-block w-auto ms-2">
    <option value="">All Sources</option>
    <?php foreach ($sources as $source): ?>
        <option value="<?= htmlspecialchars($source) ?>" <?= $selectedSource === $source ? 'selected' : '' ?>>
            <?= htmlspecialchars($source) ?>
        </option>
    <?php endforeach; ?>
</select>
    <label for="inactive_days">Only show users who haven't logged in for:</label>
    
    <select name="inactive_days" class="form-select d-inline-block w-auto ms-2">
        <option value="">All Time</option>
        <option value="1" <?= ($_GET['inactive_days'] ?? '') === '1' ? 'selected' : '' ?>>1 day</option>
        <option value="2" <?= ($_GET['inactive_days'] ?? '') === '2' ? 'selected' : '' ?>>2 days</option>
        <option value="3" <?= ($_GET['inactive_days'] ?? '') === '3' ? 'selected' : '' ?>>3 days</option>
<option value="4" <?= ($_GET['inactive_days'] ?? '') === '4' ? 'selected' : '' ?>>4 days</option>
<option value="5" <?= ($_GET['inactive_days'] ?? '') === '5' ? 'selected' : '' ?>>5 days</option>

        <option value="7" <?= ($_GET['inactive_days'] ?? '') === '7' ? 'selected' : '' ?>>7 days</option>
        <option value="14" <?= ($_GET['inactive_days'] ?? '') === '14' ? 'selected' : '' ?>>14 days</option>
        <option value="30" <?= ($_GET['inactive_days'] ?? '') === '30' ? 'selected' : '' ?>>30 days</option>
    </select>
    
    <button type="submit" class="btn btn-outline-secondary ms-2">Filter</button>

    <a href="user-referred-activity.php" class="btn btn-outline-danger ms-2">Reset Filters</a>

 
</form>


    
<form action="export-referral-activity.php" method="POST" class="mb-3">
<input type="hidden" name="source_filter" value="<?= htmlspecialchars($_GET['source_filter'] ?? '') ?>">
    <input type="hidden" name="status" value="<?= htmlspecialchars($filter) ?>">
    <input type="hidden" name="inactive_days" value="<?= htmlspecialchars($_GET['inactive_days'] ?? '') ?>">
    <button type="submit" class="btn btn-outline-success">Download CSV</button>
</form>


<form method="GET" class="mb-3">
    <input type="text" name="search" class="form-control" placeholder="Search by email or user ID..." value="<?= htmlspecialchars($_GET['search'] ?? '') ?>" style="max-width: 300px;">
</form>

    <div class="table-responsive">
    <table class="table table-bordered table-hover">
<thead>
    <tr>
        <th>First Name</th>
        <th>User ID</th>
        <th>Email</th>
        <th>Tracking Source</th>
        <th>Logins</th>
        <th>Last Login</th>
        <th>LeadsLeap ID</th>
        <th>List Campaigns</th>
        <th>Programs</th>
        <th>Status</th>
        <th>Email</th>
    </tr>
</thead>

        <tbody>
<?php foreach ($rows as $row): ?>
<?php
    // Get user_id of the referral
    $referredUserId = $row['user_id'];

    // Count how many signups this referral has
    $stmtBadge = $pdo->prepare("SELECT COUNT(*) FROM users WHERE referrer_id = ?");
    $stmtBadge->execute([$referredUserId]);
    $refCount = $stmtBadge->fetchColumn();

    // Decide which badge to show based on milestones
    $badge = '';
    if ($refCount >= 25) {
        $badge = 'signup-badge_25.png';
    } elseif ($refCount >= 10) {
        $badge = 'signup-badge_10.png';
    } elseif ($refCount >= 3) {
        $badge = 'signup-badge_03.png';
    } elseif ($refCount >= 1) {
        $badge = 'signup-badge_01.png';
    }
?>

    <?php
        $active = (
    isset($row['program_ids_set'], $row['leadsleap_id_set'], $row['leadsleap_lists_set']) &&
    $row['program_ids_set'] == 1 &&
    $row['leadsleap_id_set'] == 1 &&
    $row['leadsleap_lists_set'] == 1
);

$badgeFilename = $active ? 'badge-active.png' : 'badge-inactive.png';
$badgeAlt = $active ? 'Active User' : 'Inactive User';
    ?>
    <tr>
        <td>
    <img src="images/badges/<?= $badgeFilename ?>" alt="<?= $badgeAlt ?>" width="20" height="20" style="margin-right: 6px; vertical-align: middle; opacity: 0.8;">
    <?= htmlspecialchars($row['first_name']) ?>
    <?php if ($badge): ?>
        <img src="images/badges/<?= $badge ?>" alt="Badge" width="26" style="margin-left: 5px; vertical-align: middle;" title="<?= $refCount ?>+ Signups">
    <?php endif; ?>
</td>
        <td><?= htmlspecialchars($row['user_id']) ?></td>
        <td><?= htmlspecialchars($row['email']) ?></td>
        <td><?= htmlspecialchars($row['tracking_source'] ?? 'Unknown') ?></td>
        <td><?= $row['logins'] ?></td>
        <td><?= $row['last_login'] ?></td>
        <td><?= $row['leadsleap_id_set'] ? '✅' : '❌' ?></td>
        <td>
            <?php
                $lists = (int)$row['leadsleap_lists_set'];
                echo match ($lists) {
                    1 => '✅',
                    -1 => '⚠️',
                    default => '❌'
                };
            ?>
        </td>
        <td><?= $row['program_ids_set'] ? '✅' : '❌' ?></td>
        <td><span class="<?= $active ? 'text-success' : 'text-danger' ?>"><?= $active ? 'Active' : 'Inactive' ?></span></td>
        <td><?php
$recipientName = $row['first_name'] ?? 'there';
$senderName = $_SESSION['logged_in_user_name'] ?? 'Your Sponsor';

if ($active) {
    $subject = "You're off to a strong start!";
    $body = "Hi $recipientName,\n\nJust wanted to say well done on getting everything set up!\nYou're making great progress — keep it going!\n\n– $senderName";
} else {
    $subject = "Need a hand getting started?";
    $body = "Hi $recipientName,\n\nLooks like you're still in the setup process.\nIf you’d like help getting things moving, feel free to reply — I’m here to support you!\n\n– $senderName";
}

$mailto = "mailto:" . rawurlencode($row['email']) . "?subject=" . rawurlencode($subject) . "&body=" . rawurlencode($body);
?>
<a href="<?= $mailto ?>" class="btn btn-sm btn-outline-primary">Email</a>
</td>
    </tr>
<?php endforeach; ?>

        </tbody>
    </table>
    
    <form method="GET" class="mb-3 d-inline-block">
    <input type="hidden" name="status" value="<?= htmlspecialchars($_GET['status'] ?? '') ?>">
    <input type="hidden" name="inactive_days" value="<?= htmlspecialchars($_GET['inactive_days'] ?? '') ?>">

    <label for="sort">Sort by:</label>
    <select name="sort" class="form-select d-inline-block w-auto ms-2">
        <option value="recent" <?= ($_GET['sort'] ?? '') === 'recent' ? 'selected' : '' ?>>Most Recently Active</option>
        <option value="inactive" <?= ($_GET['sort'] ?? '') === 'inactive' ? 'selected' : '' ?>>Longest Inactive</option>
    </select>
    <button type="submit" class="btn btn-outline-secondary ms-2">Apply</button>
</form>


</div>
    
<?php $currentParams = $_GET; ?>

<nav>
<ul class="pagination">
    <?php
    if ($page > 1) {
        $params = $currentParams;
        $params['page'] = $page - 1;
        echo '<li class="page-item"><a class="page-link" href="?' . http_build_query($params) . '">Previous</a></li>';
    }

    echo '<li class="page-item disabled"><span class="page-link">Page ' . $page . ' of ' . $totalPages . '</span></li>';

    if ($page < $totalPages) {
        $params = $currentParams;
        $params['page'] = $page + 1;
        echo '<li class="page-item"><a class="page-link" href="?' . http_build_query($params) . '">Next</a></li>';
    }
    ?>
</ul>
</nav>


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