<?php
/**
 * 管理后台统计数据API
 */
require_once '../config.php';

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

// 检查登录和权限
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$user = currentUser();
if ($user['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => '无权限访问']);
    exit;
}

$type = $_GET['type'] ?? 'dashboard';
$days = intval($_GET['days'] ?? 30);

if ($type === 'dashboard') {
    // 总览数据
    $total_users = $db->fetchOne("SELECT COUNT(*) as count FROM users")['count'] ?? 0;
    $total_orders = $db->fetchOne("SELECT COUNT(*) as count FROM orders WHERE status = 'paid'")['count'] ?? 0;
    $total_amount = $db->fetchOne("SELECT SUM(amount) as total FROM orders WHERE status = 'paid'")['total'] ?? 0;
    $total_encrypts = $db->fetchOne("SELECT COUNT(*) as count FROM encrypt_history")['count'] ?? 0;
    
    // 今日新增用户
    $today_users = $db->fetchOne("SELECT COUNT(*) as count FROM users WHERE DATE(created_at) = CURDATE()")['count'] ?? 0;
    // 今日充值
    $today_amount = $db->fetchOne("SELECT SUM(amount) as total FROM orders WHERE status = 'paid' AND DATE(paid_at) = CURDATE()")['total'] ?? 0;
    
    echo json_encode([
        'success' => true,
        'data' => [
            'total_users' => $total_users,
            'total_orders' => $total_orders,
            'total_amount' => number_format($total_amount, 2),
            'total_encrypts' => $total_encrypts,
            'today_users' => $today_users,
            'today_amount' => number_format($today_amount, 2),
        ]
    ]);
    exit;
}

if ($type === 'user_trend') {
    // 用户增长趋势（最近30天）
    $data = [];
    for ($i = $days - 1; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $count = $db->fetchOne("SELECT COUNT(*) as count FROM users WHERE DATE(created_at) <= '$date'")['count'] ?? 0;
        $data[] = [
            'date' => $date,
            'count' => $count
        ];
    }
    echo json_encode(['success' => true, 'data' => $data]);
    exit;
}

if ($type === 'recharge_trend') {
    // 充值趋势（最近30天）
    $data = [];
    for ($i = $days - 1; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $amount = $db->fetchOne("SELECT SUM(amount) as total FROM orders WHERE status = 'paid' AND type = 'recharge' AND DATE(paid_at) = '$date'")['total'] ?? 0;
        $data[] = [
            'date' => $date,
            'amount' => number_format($amount, 2)
        ];
    }
    echo json_encode(['success' => true, 'data' => $data]);
    exit;
}

if ($type === 'encrypt_trend') {
    // 加密使用趋势（最近30天）
    $data = [];
    for ($i = $days - 1; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $count = $db->fetchOne("SELECT COUNT(*) as count FROM encrypt_history WHERE DATE(created_at) = '$date'")['count'] ?? 0;
        $data[] = [
            'date' => $date,
            'count' => $count
        ];
    }
    echo json_encode(['success' => true, 'data' => $data]);
    exit;
}

if ($type === 'top_users') {
    // 充值最多的用户
    $top_users = $db->fetchAll("
        SELECT u.id, u.username, u.email, SUM(o.amount) as total
        FROM orders o
        JOIN users u ON o.user_id = u.id
        WHERE o.status = 'paid' AND o.type = 'recharge'
        GROUP BY o.user_id
        ORDER BY total DESC
        LIMIT 10
    ");
    echo json_encode(['success' => true, 'data' => $top_users]);
    exit;
}

echo json_encode(['success' => false, 'message' => '无效的请求类型']);