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

$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$type = isset($_GET['type']) ? $_GET['type'] : 'all';

// Generate date range
$dates = array();
$current = strtotime($start_date);
$end = strtotime($end_date);

while ($current <= $end) {
    $dates[date('Y-m-d', $current)] = 0;
    $current = strtotime('+1 day', $current);
}

// Get daily commission data
$sql = "SELECT 
          DATE(created_at) as date,
          SUM(amount) as total_amount
        FROM referral_transactions
        WHERE created_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59'";

if ($user_id > 0) {
    $sql .= " AND referrer_id = $user_id";
}

if ($type != 'all') {
    $sql .= " AND transaction_type = '$type'";
}

$sql .= " GROUP BY DATE(created_at) ORDER BY date";

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

while ($row = mysqli_fetch_assoc($result)) {
    $dates[$row['date']] = floatval($row['total_amount']);
}

// Prepare response
$labels = array();
$amounts = array();

foreach ($dates as $date => $amount) {
    $labels[] = date('M d', strtotime($date));
    $amounts[] = $amount;
}

echo json_encode(array(
    'success' => true,
    'labels' => $labels,
    'amounts' => $amounts
));
?>