<?php
session_start();
include('includes/config.php');

// Get parameters
$format = isset($_GET['format']) ? $_GET['format'] : 'csv';
$period = isset($_GET['period']) ? $_GET['period'] : 'this_month';
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;

// Same query as in top_referrers.php
$sql = "SELECT 
            u.id,
            u.username,
            u.email,
            u.status,
            COUNT(DISTINCT r.referred_id) as total_referrals,
            COALESCE(SUM(rt.amount), 0) as total_earnings,
            u.referral_balance,
            MAX(r.created_at) as last_referral
        FROM users u
        LEFT JOIN referrals r ON u.id = r.user_id
        LEFT JOIN referral_transactions rt ON u.id = rt.referrer_id
        WHERE u.id IN (SELECT DISTINCT user_id FROM referrals)
        GROUP BY u.id, u.username, u.email, u.status, u.referral_balance
        ORDER BY total_referrals DESC
        LIMIT $limit";

$result = mysqli_query($conn, $sql);

if ($format == 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="top_referrers_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Add headers
    fputcsv($output, array('Rank', 'Username', 'Email', 'Status', 'Total Referrals', 'Total Earnings', 'Referral Balance', 'Last Referral'));
    
    // Add data
    $rank = 1;
    while ($row = mysqli_fetch_assoc($result)) {
        fputcsv($output, array(
            $rank++,
            $row['username'],
            $row['email'],
            $row['status'],
            $row['total_referrals'],
            $row['total_earnings'],
            $row['referral_balance'],
            $row['last_referral']
        ));
    }
    
    fclose($output);
    
} elseif ($format == 'excel') {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="top_referrers_' . date('Y-m-d') . '.xls"');
    
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>Rank</th>';
    echo '<th>Username</th>';
    echo '<th>Email</th>';
    echo '<th>Status</th>';
    echo '<th>Total Referrals</th>';
    echo '<th>Total Earnings</th>';
    echo '<th>Referral Balance</th>';
    echo '<th>Last Referral</th>';
    echo '</tr>';
    
    $rank = 1;
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<tr>';
        echo '<td>' . $rank++ . '</td>';
        echo '<td>' . $row['username'] . '</td>';
        echo '<td>' . $row['email'] . '</td>';
        echo '<td>' . $row['status'] . '</td>';
        echo '<td>' . $row['total_referrals'] . '</td>';
        echo '<td>' . $row['total_earnings'] . '</td>';
        echo '<td>' . $row['referral_balance'] . '</td>';
        echo '<td>' . $row['last_referral'] . '</td>';
        echo '</tr>';
    }
    
    echo '</table>';
    
} elseif ($format == 'pdf') {
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="top_referrers_' . date('Y-m-d') . '.pdf"');
    
    echo '<h1>Top Referrers Report</h1>';
    echo '<p>Generated on: ' . date('Y-m-d H:i:s') . '</p>';
    echo '<p>Period: ' . ucfirst(str_replace('_', ' ', $period)) . '</p>';
    echo '<table border="1" cellpadding="5" cellspacing="0">';
    echo '<tr>';
    echo '<th>Rank</th>';
    echo '<th>Username</th>';
    echo '<th>Email</th>';
    echo '<th>Status</th>';
    echo '<th>Total Referrals</th>';
    echo '<th>Total Earnings</th>';
    echo '</tr>';
    
    $rank = 1;
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<tr>';
        echo '<td>' . $rank++ . '</td>';
        echo '<td>' . $row['username'] . '</td>';
        echo '<td>' . $row['email'] . '</td>';
        echo '<td>' . $row['status'] . '</td>';
        echo '<td>' . $row['total_referrals'] . '</td>';
        echo '<td>$' . $row['total_earnings'] . '</td>';
        echo '</tr>';
    }
    
    echo '</table>';
}
?>