<?php
// backend/api/update-user-status.php
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');

require_once '../config/db.php';

$wallet = $_GET['wallet'] ?? '';

if(empty($wallet)) {
    echo json_encode(["status" => "error", "message" => "Wallet address required"]);
    exit;
}

// 🔥 IMPORTANT: Change 'users' to your actual table name
// Options: 'user', 'tbl_users', 'leo_users', etc.
$usersTable = 'users'; // ← CHANGE THIS to your actual table name

// Get user's total investment
$invQuery = mysqli_query($conn, "SELECT COALESCE(SUM(amount), 0) as total FROM deposits WHERE wallet = '$wallet' AND status = 'success'");
$invResult = mysqli_fetch_assoc($invQuery);
$totalInvestment = floatval($invResult['total']);

// Determine status based on investment
$newStatus = ($totalInvestment > 0) ? 'active' : 'inactive';

// Update status in users table
$updateQuery = "UPDATE $usersTable SET status = '$newStatus' WHERE wallet = '$wallet'";
$updateResult = mysqli_query($conn, $updateQuery);

if($updateResult) {
    echo json_encode([
        "status" => "success",
        "user_status" => $newStatus,
        "total_investment" => $totalInvestment,
        "message" => "Status updated successfully"
    ]);
} else {
    echo json_encode([
        "status" => "error",
        "message" => "Failed to update status: " . mysqli_error($conn)
    ]);
}
?>