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

$referrer_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($referrer_id > 0) {
    // Get referrer details
    $sql = "SELECT u.*, 
                   COUNT(DISTINCT r.referred_id) as total_referrals,
                   COUNT(DISTINCT CASE WHEN u2.status = 'verified' THEN r.referred_id END) as verified_referrals,
                   COALESCE(SUM(rt.amount), 0) as total_earnings
            FROM users u
            LEFT JOIN referrals r ON u.id = r.user_id
            LEFT JOIN users u2 ON r.referred_id = u2.id
            LEFT JOIN referral_transactions rt ON u.id = rt.referrer_id
            WHERE u.id = $referrer_id
            GROUP BY u.id";
    
    $result = mysqli_query($conn, $sql);
    $referrer = mysqli_fetch_assoc($result);
    
    // Get recent referrals
    $ref_sql = "SELECT r.*, u.username, u.email, u.status, u.registration_date 
                FROM referrals r
                LEFT JOIN users u ON r.referred_id = u.id
                WHERE r.user_id = $referrer_id
                ORDER BY r.created_at DESC
                LIMIT 10";
    $ref_result = mysqli_query($conn, $ref_sql);
    
    // Get referral transactions
    $txn_sql = "SELECT * FROM referral_transactions 
                WHERE referrer_id = $referrer_id
                ORDER BY created_at DESC
                LIMIT 10";
    $txn_result = mysqli_query($conn, $txn_sql);
    
    if ($referrer) {
        echo '<div class="row">';
        echo '<div class="col-md-6">';
        echo '<h6>Referrer Information</h6>';
        echo '<table class="table table-sm">';
        echo '<tr><td><strong>Username:</strong></td><td>' . htmlspecialchars($referrer['username']) . '</td></tr>';
        echo '<tr><td><strong>Email:</strong></td><td>' . htmlspecialchars($referrer['email']) . '</td></tr>';
        echo '<tr><td><strong>Status:</strong></td><td><span class="badge bg-' . ($referrer['status'] == 'verified' ? 'success' : 'warning') . '">' . ucfirst($referrer['status']) . '</span></td></tr>';
        echo '<tr><td><strong>Referral Balance:</strong></td><td class="text-success fw-500">$' . number_format($referrer['referral_balance'], 2) . '</td></tr>';
        echo '<tr><td><strong>Total Earnings:</strong></td><td class="text-primary fw-500">$' . number_format($referrer['total_earnings'], 2) . '</td></tr>';
        echo '</table>';
        echo '</div>';
        
        echo '<div class="col-md-6">';
        echo '<h6>Referral Statistics</h6>';
        echo '<table class="table table-sm">';
        echo '<tr><td><strong>Total Referrals:</strong></td><td>' . $referrer['total_referrals'] . '</td></tr>';
        echo '<tr><td><strong>Verified Referrals:</strong></td><td>' . $referrer['verified_referrals'] . '</td></tr>';
        echo '<tr><td><strong>Conversion Rate:</strong></td><td>' . ($referrer['total_referrals'] > 0 ? round(($referrer['verified_referrals'] / $referrer['total_referrals']) * 100, 2) : 0) . '%</td></tr>';
        echo '<tr><td><strong>Avg. per Referral:</strong></td<td>$' . ($referrer['total_referrals'] > 0 ? number_format($referrer['total_earnings'] / $referrer['total_referrals'], 2) : 0) . '</td></tr>';
        echo '</table>';
        echo '</div>';
        echo '</div>';
        
        echo '<div class="row mt-3">';
        echo '<div class="col-12">';
        echo '<h6>Recent Referrals</h6>';
        echo '<div class="table-responsive">';
        echo '<table class="table table-sm">';
        echo '<thead><tr><th>Referred User</th><th>Status</th><th>Joined Date</th><th>Referral Date</th></tr></thead>';
        echo '<tbody>';
        if (mysqli_num_rows($ref_result) > 0) {
            while ($ref = mysqli_fetch_assoc($ref_result)) {
                $status_color = $ref['status'] == 'verified' ? 'success' : ($ref['status'] == 'pending' ? 'warning' : 'secondary');
                echo '<tr>';
                echo '<td>' . htmlspecialchars($ref['username']) . '<br><small>' . htmlspecialchars($ref['email']) . '</small></td>';
                echo '<td><span class="badge bg-' . $status_color . '">' . ucfirst($ref['status']) . '</span></td>';
                echo '<td>' . date('M d, Y', strtotime($ref['registration_date'])) . '</td>';
                echo '<td>' . date('M d, Y', strtotime($ref['created_at'])) . '</td>';
                echo '</tr>';
            }
        } else {
            echo '<tr><td colspan="4" class="text-center">No referrals yet</td></tr>';
        }
        echo '</tbody></table></div></div></div>';
        
        echo '<div class="row mt-3">';
        echo '<div class="col-12">';
        echo '<h6>Recent Bonus Transactions</h6>';
        echo '<div class="table-responsive">';
        echo '<table class="table table-sm">';
        echo '<thead><tr><th>Date</th><th>Type</th><th>Amount</th><th>Description</th></tr></thead>';
        echo '<tbody>';
        if (mysqli_num_rows($txn_result) > 0) {
            while ($txn = mysqli_fetch_assoc($txn_result)) {
                $type_color = $txn['transaction_type'] == 'bot_bonus' ? 'success' : 'primary';
                echo '<tr>';
                echo '<td>' . date('M d, Y', strtotime($txn['created_at'])) . '</td>';
                echo '<td><span class="badge bg-' . $type_color . '">' . str_replace('_', ' ', ucfirst($txn['transaction_type'])) . '</span></td>';
                echo '<td class="text-success fw-500">$' . number_format($txn['amount'], 2) . '</td>';
                echo '<td><small>' . htmlspecialchars($txn['description']) . '</small></td>';
                echo '</tr>';
            }
        } else {
            echo '<tr><td colspan="4" class="text-center">No bonus transactions yet</td></tr>';
        }
        echo '</tbody></table></div></div></div>';
    } else {
        echo '<div class="alert alert-danger">Referrer not found</div>';
    }
} else {
    echo '<div class="alert alert-danger">Invalid referrer ID</div>';
}
?>