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

$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$bot_plan_id = isset($_GET['bot_plan_id']) ? intval($_GET['bot_plan_id']) : 0;
$type = isset($_GET['type']) ? $_GET['type'] : 'all';

// Build query
$sql = "SELECT 
          SUM(amount) as total_commission,
          COUNT(DISTINCT referrer_id) as unique_referrers,
          SUM(CASE WHEN transaction_type = 'signup_bonus' THEN amount ELSE 0 END) as total_signup_bonus,
          SUM(CASE WHEN transaction_type = 'bot_bonus' THEN amount ELSE 0 END) as total_bot_commission,
          SUM(CASE WHEN transaction_type = 'interest_discount' THEN amount ELSE 0 END) as total_referral_bonus,
          COUNT(*) as total_referred_users
        FROM referral_transactions rt
        WHERE rt.created_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59'";

if ($user_id > 0) {
    $sql .= " AND rt.referrer_id = $user_id";
}

if ($type != 'all') {
    $sql .= " AND rt.transaction_type = '$type'";
}

if ($bot_plan_id > 0) {
    $sql .= " AND EXISTS (
        SELECT 1 FROM user_bot_subscriptions s 
        WHERE s.user_id = rt.referred_id 
        AND s.bot_plan_id = $bot_plan_id
        AND rt.transaction_type = 'bot_bonus'
    )";
}

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

echo json_encode(array(
    'success' => true,
    'total_commission' => number_format($row['total_commission'] ?: 0, 2),
    'unique_referrers' => $row['unique_referrers'] ?: 0,
    'total_signup_bonus' => number_format($row['total_signup_bonus'] ?: 0, 2),
    'total_bot_commission' => number_format($row['total_bot_commission'] ?: 0, 2),
    'total_referral_bonus' => number_format($row['total_referral_bonus'] ?: 0, 2),
    'total_referred_users' => $row['total_referred_users'] ?: 0
));
?>