<?php
require_once("_guard.php");
function metric($conn, $sql) { $r=$conn->query($sql); $v=$r?$r->fetch_assoc():[]; return (float)($v['v']??0); }
$metrics = [
  "users" => metric($conn,"SELECT COUNT(*) v FROM users"),
  "newUsers" => metric($conn,"SELECT COUNT(*) v FROM users WHERE created_at >= CURDATE()"),
  "realBalances" => metric($conn,"SELECT COALESCE(SUM(balance),0) v FROM users"),
  "deposits" => metric($conn,"SELECT COALESCE(SUM(amount_usd),0) v FROM deposits WHERE status='success'"),
  "pendingDeposits" => metric($conn,"SELECT COUNT(*) v FROM deposits WHERE status='pending'"),
  "pendingWithdrawals" => metric($conn,"SELECT COUNT(*) v FROM crypto_withdrawals WHERE status='pending'") + metric($conn,"SELECT COUNT(*) v FROM mpesa_withdrawals WHERE status='pending'"),
  "pendingVerifications" => metric($conn,"SELECT COUNT(*) v FROM user_verifications WHERE status='pending'")
];
$activity=[]; $r=$conn->query("SELECT DATE(created_at) day, COUNT(*) users FROM users WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY) GROUP BY DATE(created_at) ORDER BY day"); while($r && ($x=$r->fetch_assoc())) $activity[]=$x;
$recent=[]; $r=$conn->query("SELECT u.id,u.full_name,u.email,u.balance,u.created_at,COALESCE(v.status,'not_submitted') verification FROM users u LEFT JOIN user_verifications v ON v.user_id=u.id ORDER BY u.created_at DESC LIMIT 8"); while($r && ($x=$r->fetch_assoc())) $recent[]=$x;
echo json_encode(["success"=>true,"metrics"=>$metrics,"activity"=>$activity,"recentUsers"=>$recent]);
?>
