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

$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

// Get updated stats
function getUpdatedStats($date) {
    global $conn;
    
    $stats = array();
    
    // Total Users (all time)
    $sql = "SELECT COUNT(*) as total FROM users";
    $result = mysqli_query($conn, $sql);
    $stats['total_users'] = mysqli_fetch_assoc($result)['total'];
    
    // New Users Today
    $sql = "SELECT COUNT(*) as total FROM users WHERE DATE(registration_date) = '$date'";
    $result = mysqli_query($conn, $sql);
    $stats['new_users'] = mysqli_fetch_assoc($result)['total'];
    
    // Today's Profit
    $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);
    $stats['today_profit'] = mysqli_fetch_assoc($result)['total'];
    
    // Total Profit (all time)
    $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM transactions WHERE type = 'profit' AND status = 'completed'";
    $result = mysqli_query($conn, $sql);
    $stats['total_profit'] = mysqli_fetch_assoc($result)['total'];
    
    // Deposits Today
    $sql = "SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as amount FROM deposits WHERE DATE(created_at) = '$date' AND status = 'confirmed'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $stats['deposits_count'] = $row['count'];
    $stats['deposits_amount'] = $row['amount'];
    
    // Withdrawals Today
    $sql = "SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as amount FROM withdrawals WHERE DATE(created_at) = '$date' AND status = 'completed'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $stats['withdrawals_count'] = $row['count'];
    $stats['withdrawals_amount'] = $row['amount'];
    
    return $stats;
}

$stats = getUpdatedStats($date);

echo json_encode(array(
    'success' => true,
    'total_users' => $stats['total_users'],
    'new_users' => $stats['new_users'],
    'today_profit' => $stats['today_profit'],
    'total_profit' => $stats['total_profit'],
    'deposits_count' => $stats['deposits_count'],
    'deposits_amount' => $stats['deposits_amount'],
    'withdrawals_count' => $stats['withdrawals_count'],
    'withdrawals_amount' => $stats['withdrawals_amount']
));
?>