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

$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-01');
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-t');

// Total Revenue
$sql = "SELECT COALESCE(SUM(subscription_fee), 0) as total FROM user_bot_subscriptions 
        WHERE subscription_start BETWEEN '$date_from' AND '$date_to' AND status = 'active'";
$result = mysqli_query($conn, $sql);
$subscription_revenue = mysqli_fetch_assoc($result)['total'];

$sql = "SELECT COALESCE(SUM(amount), 0) as total FROM deposits 
        WHERE created_at BETWEEN '$date_from' AND '$date_to' AND status = 'confirmed'";
$result = mysqli_query($conn, $sql);
$deposit_revenue = mysqli_fetch_assoc($result)['total'];

$total_revenue = $subscription_revenue + $deposit_revenue;

// Total Expenses
$sql = "SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals 
        WHERE created_at BETWEEN '$date_from' AND '$date_to' AND status = 'completed'";
$result = mysqli_query($conn, $sql);
$withdrawal_expenses = mysqli_fetch_assoc($result)['total'];

// Fee Income
$sql = "SELECT COALESCE(SUM(fee), 0) as total FROM withdrawals 
        WHERE created_at BETWEEN '$date_from' AND '$date_to' AND status = 'completed'";
$result = mysqli_query($conn, $sql);
$fee_income = mysqli_fetch_assoc($result)['total'];

// Trading Profit
$sql = "SELECT COALESCE(SUM(amount), 0) as total FROM transactions 
        WHERE type = 'profit' AND status = 'completed' 
        AND DATE(date) BETWEEN '$date_from' AND '$date_to'";
$result = mysqli_query($conn, $sql);
$trading_profit = mysqli_fetch_assoc($result)['total'];

// Net Profit
$net_profit = $total_revenue + $fee_income + $trading_profit - $withdrawal_expenses;

echo json_encode(array(
    'success' => true,
    'total_revenue' => number_format($total_revenue, 2),
    'subscription_revenue' => number_format($subscription_revenue, 2),
    'deposit_revenue' => number_format($deposit_revenue, 2),
    'withdrawal_expenses' => number_format($withdrawal_expenses, 2),
    'fee_income' => number_format($fee_income, 2),
    'trading_profit' => number_format($trading_profit, 2),
    'net_profit' => number_format($net_profit, 2)
));
?>