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

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

$chart = isset($_GET['chart']) ? $_GET['chart'] : 'revenue';
$period = isset($_GET['period']) ? intval($_GET['period']) : 7;

$response = array('success' => false);

if ($chart == 'revenue') {
    // Generate labels for the period
    $labels = array();
    $revenue_data = array();
    $profit_data = array();
    
    for ($i = $period - 1; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $labels[] = date('M d', strtotime($date));
        
        // Get revenue for this day (subscription fees + deposits)
        $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM (
            SELECT subscription_fee as amount FROM user_bot_subscriptions WHERE DATE(subscription_start) = '$date'
            UNION ALL
            SELECT amount FROM deposits WHERE DATE(created_at) = '$date' AND status = 'confirmed'
        ) as combined";
        $result = mysqli_query($conn, $sql);
        $row = mysqli_fetch_assoc($result);
        $revenue_data[] = floatval($row['total']);
        
        // Get profit for this day
        $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM transactions WHERE type = 'profit' AND status = 'completed' AND DATE(date) = '$date'";
        $result = mysqli_query($conn, $sql);
        $row = mysqli_fetch_assoc($result);
        $profit_data[] = floatval($row['total']);
    }
    
    $response = array(
        'success' => true,
        'labels' => $labels,
        'revenue' => $revenue_data,
        'profit' => $profit_data
    );
    
} elseif ($chart == 'bot_plan') {
    // Get bot plan distribution
    $sql = "SELECT p.plan_name, COUNT(s.id) as count 
            FROM trading_bot_plans p 
            LEFT JOIN user_bot_subscriptions s ON p.id = s.bot_plan_id AND s.status = 'active'
            WHERE p.is_active = 1
            GROUP BY p.id
            ORDER BY p.sort_order";
    $result = mysqli_query($conn, $sql);
    
    $labels = array();
    $series = array();
    
    while ($row = mysqli_fetch_assoc($result)) {
        $labels[] = $row['plan_name'];
        $series[] = intval($row['count']);
    }
    
    $response = array(
        'success' => true,
        'labels' => $labels,
        'series' => $series
    );
}

echo json_encode($response);
?>