<?php
require_once 'db.php';

$user_id = $_POST['user_id'] ?? null;
$sourceFilter = $_POST['source_filter'] ?? '';

if (!$user_id) {
    die("Invalid request.");
}

if (!empty($sourceFilter)) {
    $stmt = $pdo->prepare("SELECT user_id, first_name, last_name, email, tracking_source, created_at 
                           FROM users 
                           WHERE referrer_id = ? AND tracking_source = ?
                           ORDER BY created_at DESC");
    $stmt->execute([$user_id, $sourceFilter]);
} else {
    $stmt = $pdo->prepare("SELECT user_id, first_name, last_name, email, tracking_source, created_at 
                           FROM users 
                           WHERE referrer_id = ?
                           ORDER BY created_at DESC");
    $stmt->execute([$user_id]);
}

$referrals = $stmt->fetchAll();

// ✅ Generate CSV
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="referrals.csv"');

$output = fopen('php://output', 'w');
fputcsv($output, ['Name', 'Username', 'Email', 'Tracking Source', 'Joined']);

foreach ($referrals as $referral) {
    fputcsv($output, [
        $referral['first_name'] . " " . $referral['last_name'],
        $referral['user_id'],
        $referral['email'],
        $referral['tracking_source'] ?? 'Unknown',
        !empty($referral['created_at']) ? date('Y-m-d', strtotime($referral['created_at'])) : ''
    ]);
}

fclose($output);
exit;
