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

// Get referral statistics
$stats_sql = "SELECT 
    (SELECT COUNT(*) FROM referrals) as total_referrals,
    (SELECT COUNT(DISTINCT referred_by) FROM referrals WHERE referred_by IS NOT NULL) as total_referrers,
    (SELECT COUNT(*) FROM users WHERE referred_by IS NOT NULL) as referred_users,
    (SELECT COALESCE(SUM(amount), 0) FROM referral_transactions) as total_bonus_paid";

$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

// Get program status
$settings_sql = "SELECT is_active FROM referral_settings WHERE id = 1";
$settings_result = mysqli_query($conn, $settings_sql);
$settings = mysqli_fetch_assoc($settings_result);

echo json_encode(array(
    'success' => true,
    'total_referrals' => $stats['total_referrals'],
    'total_referrers' => $stats['total_referrers'],
    'referred_users' => $stats['referred_users'],
    'total_bonus_paid' => number_format($stats['total_bonus_paid'], 2),
    'is_active' => isset($settings['is_active']) ? $settings['is_active'] : 0
));
?>