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

$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-d', strtotime('-30 days'));
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');

// Calculate totals
$total_revenue = 0;
$total_profit = 0;
$total_fees = 0;
$total_subscriptions = 0;
$total_deposits = 0;
$total_withdrawals = 0;

// Get subscription revenue
$sub_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'";
$sub_result = mysqli_query($conn, $sub_sql);
$sub_row = mysqli_fetch_assoc($sub_result);
$total_subscriptions = $sub_row['total'];

// Get deposit revenue
$deposit_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM deposits 
                WHERE status = 'confirmed' 
                AND DATE(created_at) BETWEEN '$date_from' AND '$date_to'";
$deposit_result = mysqli_query($conn, $deposit_sql);
$deposit_row = mysqli_fetch_assoc($deposit_result);
$total_deposits = $deposit_row['total'];

// Get withdrawal amounts
$withdrawal_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals 
                   WHERE status = 'completed' 
                   AND DATE(created_at) BETWEEN '$date_from' AND '$date_to'";
$withdrawal_result = mysqli_query($conn, $withdrawal_sql);
$withdrawal_row = mysqli_fetch_assoc($withdrawal_result);
$total_withdrawals = $withdrawal_row['total'];

// Get trading profit
$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'";
$profit_result = mysqli_query($conn, $profit_sql);
$profit_row = mysqli_fetch_assoc($profit_result);
$total_profit = $profit_row['total'];

// Get fees
$fees_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM transactions 
             WHERE type = 'fee' AND status = 'completed' 
             AND DATE(date) BETWEEN '$date_from' AND '$date_to'";
$fees_result = mysqli_query($conn, $fees_sql);
$fees_row = mysqli_fetch_assoc($fees_result);
$total_fees = $fees_row['total'];

// Calculate totals
$total_revenue = $total_subscriptions + $total_deposits + $total_profit + $total_fees;
$net_profit = $total_profit + $total_fees + $total_subscriptions - $total_withdrawals;

echo json_encode(array(
    'success' => true,
    'total_revenue' => number_format($total_revenue, 2),
    'total_profit' => number_format($total_profit, 2),
    'total_fees' => number_format($total_fees, 2),
    'total_subscriptions' => number_format($total_subscriptions, 2),
    'total_deposits' => number_format($total_deposits, 2),
    'total_withdrawals' => number_format($total_withdrawals, 2),
    'net_profit' => number_format($net_profit, 2)
));
?>