<?php
require_once 'db.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    exit("Access denied");
}

// ✅ Get filters from POST
$filter = $_POST['status'] ?? '';
$inactiveDays = isset($_POST['inactive_days']) ? (int)$_POST['inactive_days'] : 0;
$search = $_POST['search'] ?? '';

$filters = [];

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)";
}

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

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

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

// ✅ Fetch users with sponsor info
$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
");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ✅ Set CSV headers
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="user-activity-export.csv"');

$output = fopen('php://output', 'w');

// ✅ CSV columns
fputcsv($output, [
    'User ID',
    'First Name',
    'Email',
    'Logins',
    'Last Login',
    'Days Inactive',
    'LeadsLeap ID',
    'List Campaigns',
    'Programs',
    'Status',
    'Suggested Subject',
    'Suggested Body',
    'Sponsor Name',
    'Sponsor Email',
]);

foreach ($rows as $row) {
    $logins = (int)($row['logins'] ?? 0);
    $lastLogin = $row['last_login'] ?? '';
    $firstName = $row['first_name'] ?? 'there';

    // ✅ Status check
    $leadsleap = (int)($row['leadsleap_id_set'] ?? 0);
    $lists = (int)($row['leadsleap_lists_set'] ?? 0);
    $programs = (int)($row['program_ids_set'] ?? 0);
    $active = $leadsleap && $lists && $programs;

    // ✅ Inactive days
    $daysInactive = '';
    if (!empty($lastLogin)) {
        $lastLoginTime = strtotime($lastLogin);
        $daysInactive = floor((time() - $lastLoginTime) / (60 * 60 * 24));
    }

    // ✅ Email content
    $senderName = "Edward Keyte";
    if ($active) {
        $subject = "$firstName, You're crushing it with MLM Lead Pro!";
        $body = "Hi $firstName,\n\nJust wanted to say congrats on getting everything set up!\nYou're doing awesome — keep up the momentum!\n\n– $senderName";
    } else {
        $subject = "$firstName, Need help getting started with MLM Lead Pro?";
        $body = "Hi $firstName,\n\nI noticed you haven't completed your setup yet.\nIf you’d like help getting things going, just reply — happy to assist!\n\n– $senderName";
    }

    // ✅ Add row to CSV
    fputcsv($output, [
        $row['user_id'],
        $row['first_name'],
        $row['email'],
        $logins,
        $lastLogin,
        $daysInactive,
        $leadsleap ? '✅' : '❌',
        match($lists) {
            1 => '✅',
            -1 => '⚠️',
            default => '❌'
        },
        $programs ? '✅' : '❌',
        $active ? 'Active' : 'Inactive',
        $subject,
        $body,
        $row['sponsor_name'] ?? '-',
        $row['sponsor_email'] ?? '-',
    ]);
}

fclose($output);
exit;
