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

header('Content-Type: application/json');

// Get parameters
$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-d');
$plan_filter = isset($_GET['plan']) ? intval($_GET['plan']) : 0;
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';

// Calculate days difference
$start = new DateTime($date_from);
$end = new DateTime($date_to);
$days = $end->diff($start)->days;

// If more than 30 days, group by month
if ($days > 30) {
    $group_by = 'MONTH';
    $date_format = 'M Y';
    $interval = '1 MONTH';
} else {
    $group_by = 'DAY';
    $date_format = 'M d';
    $interval = '1 DAY';
}

// Generate data points
$labels = [];
$revenue_data = [];
$current = new DateTime($date_from);

while ($current <= $end) {
    $period_start = $current->format('Y-m-d');
    
    if ($group_by == 'MONTH') {
        $period_end = $current->format('Y-m-t');
        $label = $current->format('M Y');
        $current->modify('+1 month');
    } else {
        $period_end = $current->format('Y-m-d');
        $label = $current->format('M d');
        $current->modify('+1 day');
    }
    
    // Get revenue for this period
    $sql = "SELECT COALESCE(SUM(p.subscription_fee), 0) as revenue
            FROM user_bot_subscriptions s
            JOIN trading_bot_plans p ON s.bot_plan_id = p.id
            WHERE DATE(s.subscription_start) BETWEEN '$period_start' AND '$period_end'";
    
    if ($plan_filter > 0) {
        $sql .= " AND s.bot_plan_id = $plan_filter";
    }
    if ($status_filter) {
        $sql .= " AND s.status = '$status_filter'";
    }
    
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    
    $labels[] = $label;
    $revenue_data[] = floatval($row['revenue']);
}

echo json_encode([
    'success' => true,
    'labels' => $labels,
    'revenue' => $revenue_data
]);
?>