<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept");

require_once "../database.php"; // Database connection script

try {
    // Total balance
    $stmt = $conn->query("SELECT SUM(balance) AS total_balance FROM users");
    $total_balance = $stmt->fetch(PDO::FETCH_ASSOC)['total_balance'];

    // Total user points
    $stmt = $conn->query("SELECT SUM(points) AS total_points FROM users");
    $total_points = $stmt->fetch(PDO::FETCH_ASSOC)['total_points'];

    // Active users
    $stmt = $conn->query("SELECT COUNT(*) AS active_users FROM users WHERE status = 'active'");
    $active_users = $stmt->fetch(PDO::FETCH_ASSOC)['active_users'];

    // Blocked users
    $stmt = $conn->query("SELECT COUNT(*) AS blocked_users FROM users WHERE status = 'blocked'");
    $blocked_users = $stmt->fetch(PDO::FETCH_ASSOC)['blocked_users'];

    // Users who have paid
    $stmt = $conn->query("SELECT COUNT(*) AS paid_users FROM users WHERE has_paid = 'yes'");
    $paid_users = $stmt->fetch(PDO::FETCH_ASSOC)['paid_users'];

    // Users with completed registration
    $stmt = $conn->query("SELECT COUNT(*) AS registered_users FROM users WHERE registration_completed = 'yes'");
    $registered_users = $stmt->fetch(PDO::FETCH_ASSOC)['registered_users'];

    echo json_encode([
        "status" => "success",
        "data" => [
            "total_balance" => (float)$total_balance,
            "total_points" => (int)$total_points,
            "active_users" => (int)$active_users,
            "blocked_users" => (int)$blocked_users,
            "paid_users" => (int)$paid_users,
            "registration_completed_users" => (int)$registered_users
        ]
    ]);
} catch (PDOException $e) {
    echo json_encode([
        "status" => "error",
        "message" => "Failed to fetch stats: " . $e->getMessage()
    ]);
}
?>
