<?php
require_once 'db.php';
session_start();

// ✅ CHECK USER ID FROM SESSION
$user_identifier = $_SESSION['logged_in_user'] ?? null;

if (!$user_identifier) {
    die("ERROR: User not logged in.");
}

// ✅ FETCH THE NUMERIC USER ID
$stmt = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$stmt->execute([$user_identifier]);
$userData = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$userData) {
    die("ERROR: User not found in the database.");
}

$numeric_user_id = $userData['id']; // Get numeric ID from users table

// ✅ Check if a filter is applied
$source_filter = $_POST['source_filter'] ?? '';

if (!empty($source_filter)) {
    $stmt = $pdo->prepare("SELECT name, email, source, created_at FROM leads WHERE user_id = ? AND source = ?");
    $stmt->execute([$numeric_user_id, $source_filter]);
} else {
    $stmt = $pdo->prepare("SELECT name, email, source, created_at FROM leads WHERE user_id = ?");
    $stmt->execute([$numeric_user_id]);
}
$leads = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($leads)) {
    die("ERROR: No leads found for this user.");
}

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

$output = fopen('php://output', 'w');
fputcsv($output, ['Name', 'Email', 'Source', 'Date Collected']); // CSV Header

foreach ($leads as $lead) {
    fputcsv($output, [$lead['name'], $lead['email'], $lead['source'] ?? 'N/A', $lead['created_at']]);
}

fclose($output);
exit;
?>
