<?php
// ✅ Start clean: prevent accidental output
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// ✅ Ensure session is active before any output
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once 'db.php';

$senderName = $_SESSION['logged_in_user_name'] ?? 'Your Sponsor';

if (!isset($_SESSION['logged_in_user'])) {
    exit("Access denied");
}

$loggedInUser = $_SESSION['logged_in_user'];
$filter = $_POST['status'] ?? '';
$selectedSource = $_POST['source_filter'] ?? '';
$inactiveDays = isset($_POST['inactive_days']) ? (int)$_POST['inactive_days'] : 0;

// ✅ Build WHERE clause
$filters = ["u.referrer_id = ?"];
$params = [$loggedInUser];

if (!empty($selectedSource)) {
    $filters[] = "u.tracking_source = ?";
    $params[] = $selectedSource;
}

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 < ?";
    $params[] = $cutoffDate;
}

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

// ✅ Fetch data
$stmt = $pdo->prepare("
    SELECT u.user_id, u.email, u.first_name, u.tracking_source, a.logins, a.last_login, 
           a.leadsleap_id_set, a.leadsleap_lists_set, a.program_ids_set
    FROM user_activity a
    JOIN users u ON a.user_id = u.user_id
    WHERE $whereClause
    ORDER BY a.last_login DESC
");
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ✅ Output headers BEFORE any content
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="referral-activity.csv"');

$output = fopen('php://output', 'w');
fputcsv($output, [
    'User ID', 'Email', 'First Name', 'Tracking Source', 'Inactive Days', 'Status',
    'Suggested Subject', 'Suggested Body', 'Login Link'
]);

foreach ($rows as $row) {
    $status = ($row['leadsleap_id_set'] && $row['leadsleap_lists_set'] && $row['program_ids_set']) ? 'Active' : 'Inactive';

    $lastLogin = strtotime($row['last_login']);
    $inactive = floor((time() - $lastLogin) / 86400);
    $firstName = trim($row['first_name'] ?? '');
    $nameForSubject = $firstName !== '' ? $firstName : 'there';
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$scriptDir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$loginLink = $protocol . $host . $scriptDir . '/user-login.php';

$inactiveSubjects = [
    "$nameForSubject, need help getting started?",
    "Everything okay $nameForSubject? Just checking in 💬",
    "$nameForSubject, let me know if you need a hand setting up 👍",
    "Noticed you haven’t finished setup — I’m here to help!",
    "$nameForSubject, want to unlock your full potential?"
];

$activeSubjects = [
    "You're off to a great start, $nameForSubject!",
    "🔥 Awesome momentum so far, $nameForSubject!",
    "$nameForSubject, you're all set — keep it up 💪",
    "Your setup looks great, $nameForSubject!",
    "$nameForSubject, you're in and rolling — let’s go!"
];


if ($status === 'Active') {
    $subject = $activeSubjects[array_rand($activeSubjects)];
    $body = "Hi $firstName,\n\nJust wanted to say well done on getting everything set up!\nYou're making great progress — keep the momentum going!\n\n– $senderName";
} else {
    $subject = $inactiveSubjects[array_rand($inactiveSubjects)];
    $body = "Hi $firstName,\n\nLooks like you're still working on your setup. If you’d like a hand or have any questions, feel free to reach out — I’m here to help!\n\n– $senderName";
}


    fputcsv($output, [
        $row['user_id'],
        $row['email'],
        $firstName,
        $row['tracking_source'] ?? 'Unknown',
        $inactive,
        $status,
        $subject,
        $body,
        $loginLink
    ]);
}

fclose($output);
exit;
?>
