<?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');
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';

// Get 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 DATE(s.subscription_start) BETWEEN '$date_from' AND '$date_to'";

if ($status_filter) {
    $sql .= " AND s.status = '$status_filter'";
}

$sql .= " WHERE p.is_active = 1
        GROUP BY p.id
        ORDER BY p.sort_order";

$result = mysqli_query($conn, $sql);

$labels = [];
$series = [];
$colors = ['#667eea', '#f093fb', '#4facfe', '#43e97b', '#fa709a'];

while ($row = mysqli_fetch_assoc($result)) {
    $labels[] = $row['plan_name'];
    $series[] = intval($row['count']);
}

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