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

// Get filter parameters
$format = isset($_GET['format']) ? $_GET['format'] : 'csv';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$type = isset($_GET['type']) ? $_GET['type'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build query
$sql = "SELECT b.*, 
               u1.username as referrer_name, 
               u1.email as referrer_email,
               u2.username as referred_name,
               u2.email as referred_email
        FROM referral_bonuses b
        LEFT JOIN users u1 ON b.referrer_id = u1.id
        LEFT JOIN users u2 ON b.referred_id = u2.id
        WHERE 1=1";

if ($status) {
    $sql .= " AND b.status = '$status'";
}

if ($type) {
    $sql .= " AND b.bonus_type = '$type'";
}

if ($search) {
    $sql .= " AND (u1.username LIKE '%$search%' OR u1.email LIKE '%$search%' OR u2.username LIKE '%$search%' OR u2.email LIKE '%$search%')";
}

if ($date_from && $date_to) {
    $sql .= " AND DATE(b.created_at) BETWEEN '$date_from' AND '$date_to'";
} elseif ($date_from) {
    $sql .= " AND DATE(b.created_at) >= '$date_from'";
} elseif ($date_to) {
    $sql .= " AND DATE(b.created_at) <= '$date_to'";
}

$sql .= " ORDER BY b.created_at DESC";
$result = mysqli_query($conn, $sql);

if ($format == 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="referral_bonuses_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Add headers
    fputcsv($output, array('ID', 'Referrer', 'Referrer Email', 'Referred User', 'Referred Email', 'Bonus Type', 'Amount', 'Status', 'Created Date', 'Paid Date', 'Payment Method', 'Description'));
    
    // Add data
    while ($row = mysqli_fetch_assoc($result)) {
        fputcsv($output, array(
            $row['id'],
            $row['referrer_name'],
            $row['referrer_email'],
            $row['referred_name'] ?: 'N/A',
            $row['referred_email'] ?: 'N/A',
            ucfirst(str_replace('_', ' ', $row['bonus_type'])),
            $row['amount'],
            ucfirst($row['status']),
            $row['created_at'],
            $row['paid_date'] ?: 'Not paid',
            $row['payment_method'] ?: 'N/A',
            $row['description'] ?: ''
        ));
    }
    
    fclose($output);
    
} elseif ($format == 'excel') {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="referral_bonuses_' . date('Y-m-d') . '.xls"');
    
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>ID</th>';
    echo '<th>Referrer</th>';
    echo '<th>Referrer Email</th>';
    echo '<th>Referred User</th>';
    echo '<th>Referred Email</th>';
    echo '<th>Bonus Type</th>';
    echo '<th>Amount</th>';
    echo '<th>Status</th>';
    echo '<th>Created Date</th>';
    echo '<th>Paid Date</th>';
    echo '<th>Payment Method</th>';
    echo '<th>Description</th>';
    echo '</tr>';
    
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<tr>';
        echo '<td>' . $row['id'] . '</td>';
        echo '<td>' . $row['referrer_name'] . '</td>';
        echo '<td>' . $row['referrer_email'] . '</td>';
        echo '<td>' . ($row['referred_name'] ?: 'N/A') . '</td>';
        echo '<td>' . ($row['referred_email'] ?: 'N/A') . '</td>';
        echo '<td>' . ucfirst(str_replace('_', ' ', $row['bonus_type'])) . '</td>';
        echo '<td>$' . $row['amount'] . '</td>';
        echo '<td>' . ucfirst($row['status']) . '</td>';
        echo '<td>' . $row['created_at'] . '</td>';
        echo '<td>' . ($row['paid_date'] ?: 'Not paid') . '</td>';
        echo '<td>' . ($row['payment_method'] ?: 'N/A') . '</td>';
        echo '<td>' . ($row['description'] ?: '') . '</td>';
        echo '</tr>';
    }
    
    echo '</table>';
}
?>