<?php
// ✅ Start session before any output
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ✅ Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

require_once 'db.php';

// Filter
$filter = $_GET['status'] ?? '';
$inactiveDays = isset($_GET['inactive_days']) ? (int)$_GET['inactive_days'] : 0;
$search = $_GET['search'] ?? '';
$limit = 50; // Show 50 users per page
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;

$filters = [];

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

if ($inactiveDays > 0) {
    $cutoffDate = date('Y-m-d H:i:s', strtotime("-$inactiveDays days"));
    $filters[] = "last_login < '$cutoffDate'";
}

if (!empty($search)) {
    $searchSafe = $pdo->quote("%$search%");
    $filters[] = "(u.email LIKE $searchSafe OR a.user_id LIKE $searchSafe)";
}

$condition = count($filters) ? 'WHERE ' . implode(' AND ', $filters) : '';

$countStmt = $pdo->query("
    SELECT COUNT(*) 
    FROM users u 
    LEFT JOIN user_activity a ON a.user_id = u.user_id
    $condition
");
$totalRows = $countStmt->fetchColumn();
$totalPages = max(1, ceil($totalRows / $limit));


$stmt = $pdo->query("
    SELECT u.user_id, u.email, u.first_name, u.referrer_id,
           r.first_name AS sponsor_name, r.email AS sponsor_email,
           a.logins, a.last_login, 
           a.leadsleap_id_set, a.leadsleap_lists_set, a.program_ids_set
    FROM users u
    LEFT JOIN users r ON u.referrer_id = r.user_id
    LEFT JOIN user_activity a ON a.user_id = u.user_id
    $condition
    ORDER BY a.last_login DESC
    LIMIT $limit OFFSET $offset
");

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
    <title>User Activity Overview</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        .filter-btn { margin-right: 10px; }
        .tick { color: green; font-weight: bold; }
        .cross { color: red; font-weight: bold; }
    </style>
</head>



<body class="p-4" style="display: flex; min-height: 100vh; margin: 0;">
<div class="admin-sidebar" style="width:220px; background:#343a40; padding:20px;">
  <?php include 'google-translate-widget-front-end.php'; ?>
  <?php include 'admin-links.php'; ?>
</div>

  <div style="flex-grow: 1; padding: 20px;">
  
  
  
  
  
  

    <h3>📊 User Activity Overview</h3>
    
    <div class="lead-summary mb-3">
    <strong>Summary:</strong>
    <ul>
        <li>Total Users: <?= $totalRows ?></li>
        <li>Filters: 
            <?= $filter ?: 'All' ?> 
            <?= $inactiveDays ? " | Inactive for $inactiveDays days+" : '' ?>
            <?= $search ? " | Search: " . htmlspecialchars($search) : '' ?>
        </li>
    </ul>
</div>

<form method="GET" class="mb-3 d-flex flex-wrap align-items-center gap-2">
    <label>Status:</label>
    <select name="status" class="form-select w-auto">
        <option value="">All</option>
        <option value="active" <?= $filter === 'active' ? 'selected' : '' ?>>Active</option>
        <option value="inactive" <?= $filter === 'inactive' ? 'selected' : '' ?>>Inactive</option>
    </select>

    <label>Inactive for:</label>
    <select name="inactive_days" class="form-select w-auto">
        <option value="">All Time</option>
        <option value="1" <?= $inactiveDays == 1 ? 'selected' : '' ?>>1 day</option>
        <option value="2" <?= $inactiveDays == 2 ? 'selected' : '' ?>>2 days</option>
        <option value="7" <?= $inactiveDays == 7 ? 'selected' : '' ?>>7 days</option>
        <option value="14" <?= $inactiveDays == 14 ? 'selected' : '' ?>>14 days</option>
        <option value="30" <?= $inactiveDays == 30 ? 'selected' : '' ?>>30 days</option>
    </select>

    <input type="text" name="search" placeholder="Search by email/user ID" class="form-control w-auto" value="<?= htmlspecialchars($search) ?>">

    <button type="submit" class="btn btn-outline-primary">Apply Filters</button>
    <a href="admin-activity.php" class="btn btn-outline-secondary">Reset</a>
</form>

    
    <div class="mb-3">
        <a href="?status=" class="btn btn-secondary filter-btn">All</a>
        <a href="?status=active" class="btn btn-success filter-btn">Active</a>
        <a href="?status=inactive" class="btn btn-danger filter-btn">Inactive</a>
    </div>
    <form action="export-admin-activity.php" method="POST" class="mb-3">
    <input type="hidden" name="status" value="<?= htmlspecialchars($filter) ?>">
    <input type="hidden" name="inactive_days" value="<?= htmlspecialchars($inactiveDays) ?>">
    <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>">
    <button type="submit" class="btn btn-outline-success">📤 Export CSV</button>
</form>
<?php if (count($rows) > 0): ?>
<form class="mb-3">
    <button type="button" class="btn btn-outline-danger" onclick="showDeleteSQL()">🗑️ Generate SQL DELETE</button>
</form>

<form class="mb-3">
    <button type="button" class="btn btn-outline-info" onclick="showLookupSQL()">🔍 Generate SQL LOOKUP</button>
</form>
<pre id="lookupSqlBox" class="bg-light p-3 rounded" style="display:none; white-space:pre-wrap;"></pre>
<button id="copyLookupBtn" class="btn btn-sm btn-secondary mt-2" style="display:none;">📋 Copy Lookup SQL</button>


<pre id="deleteSqlBox" class="bg-light p-3 rounded" style="display:none; white-space:pre-wrap;"></pre>
<button id="copySqlBtn" class="btn btn-sm btn-secondary mt-2" style="display:none;">📋 Copy SQL to Clipboard</button>

<script>
function showDeleteSQL() {
    const ids = <?= json_encode(array_column($rows, 'user_id')) ?>;
    if (ids.length === 0) return;

    const userIds = ids.map(id => `'${id}'`).join(', ');
    const sql = `
-- Delete matching users and activity
DELETE FROM user_activity WHERE user_id IN (${userIds});
DELETE FROM users WHERE user_id IN (${userIds});
`;

    const box = document.getElementById('deleteSqlBox');
    const button = document.getElementById('copySqlBtn');

    box.textContent = sql.trim();
    box.style.display = 'block';
    button.style.display = 'inline-block';

    // Save SQL for copy function
    button.dataset.sql = sql.trim();
}

document.getElementById('copySqlBtn').addEventListener('click', function() {
    navigator.clipboard.writeText(this.dataset.sql).then(() => {
        this.textContent = '✅ Copied!';
        setTimeout(() => this.textContent = '📋 Copy SQL to Clipboard', 2000);
    });
});
</script>

<script>
function showLookupSQL() {
    const ids = <?= json_encode(array_column($rows, 'user_id')) ?>;
    if (ids.length === 0) return;

    const userIds = ids.map(id => `'${id}'`).join(', ');
    const sql = `
-- Lookup user and activity (safe view only)
SELECT * FROM users WHERE user_id IN (${userIds});
SELECT * FROM user_activity WHERE user_id IN (${userIds});
`;

    const box = document.getElementById('lookupSqlBox');
    const button = document.getElementById('copyLookupBtn');

    box.textContent = sql.trim();
    box.style.display = 'block';
    button.style.display = 'inline-block';

    // Save SQL for copy function
    button.dataset.sql = sql.trim();
}

document.getElementById('copyLookupBtn').addEventListener('click', function() {
    navigator.clipboard.writeText(this.dataset.sql).then(() => {
        this.textContent = '✅ Copied!';
        setTimeout(() => this.textContent = '📋 Copy Lookup SQL', 2000);
    });
});
</script>


<?php endif; ?>

    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th>First Name</th>
                <th>User ID</th>
                <th>Email</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>
                <th>Sponsor</th>
            </tr>
        </thead>
        <tbody>
<?php foreach ($rows as $row): ?>
    <?php
        $active = ($row['leadsleap_id_set'] ?? 0) && ($row['leadsleap_lists_set'] ?? 0) && ($row['program_ids_set'] ?? 0);
    ?>
<tr>
    <td><?= htmlspecialchars($row['first_name'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['user_id']) ?></td>
    <td><?= htmlspecialchars($row['email']) ?></td>
    <td><?= $row['logins'] ?? 0 ?></td>
    <td><?= $row['last_login'] ?? '-' ?></td>
    <td><?= ($row['leadsleap_id_set'] ?? 0) ? '✅' : '❌' ?></td>
    <td>
        <?php
            $lists = (int)($row['leadsleap_lists_set'] ?? 0);
            echo match ($lists) {
                1 => '✅',
                -1 => '⚠️',
                default => '❌'
            };
        ?>
    </td>
    <td><?= ($row['program_ids_set'] ?? 0) ? '✅' : '❌' ?></td>
    <td><span class="<?= $active ? 'text-success' : 'text-danger' ?>"><?= $active ? 'Active' : 'Inactive' ?></span></td>
    <td><a href="<?= $mailto ?>" class="btn btn-sm btn-outline-primary">Email</a></td>
    <td>
        <?= htmlspecialchars($row['sponsor_name'] ?? '-') ?><br>
        <small><?= htmlspecialchars($row['sponsor_email'] ?? '-') ?></small>
    </td>
</tr>

<?php endforeach; ?>

        </tbody>
    </table>
    <?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>
<?php include 'admin-footer.php'; ?>
</div> <!-- Close main-content -->



</body>
</html>
