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

// Get filter parameters
$type = isset($_GET['type']) ? $_GET['type'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$subscription_id = isset($_GET['subscription_id']) ? intval($_GET['subscription_id']) : 0;

// Build stats query
$stats_sql = "SELECT 
    SUM(CASE WHEN transaction_type = 'profit' THEN amount ELSE 0 END) as total_profit,
    SUM(CASE WHEN transaction_type = 'loss' THEN amount ELSE 0 END) as total_loss,
    SUM(CASE WHEN transaction_type = 'fee' THEN amount ELSE 0 END) as total_fees,
    COUNT(*) as total_count
    FROM bot_transactions WHERE 1=1";

if ($type) {
    $stats_sql .= " AND transaction_type = '$type'";
}

if ($date_from && $date_to) {
    $stats_sql .= " AND transaction_date BETWEEN '$date_from' AND '$date_to'";
} elseif ($date_from) {
    $stats_sql .= " AND transaction_date >= '$date_from'";
} elseif ($date_to) {
    $stats_sql .= " AND transaction_date <= '$date_to'";
}

if ($subscription_id > 0) {
    $stats_sql .= " AND subscription_id = $subscription_id";
}

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

echo json_encode(array(
    'success' => true,
    'total_profit' => number_format($stats['total_profit'] ?: 0, 2),
    'total_loss' => number_format($stats['total_loss'] ?: 0, 2),
    'total_fees' => number_format($stats['total_fees'] ?: 0, 2),
    'total_count' => number_format($stats['total_count'] ?: 0, 0)
));
?>