<?php 
    require_once __DIR__ . '/config/config.php';
    session_start();
    header('Content-Type: application/json');

    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized.']);
        exit;
    }

    $user_id = $_SESSION['user_id'];

    // Account Balance
    $balance = 0;
    $balanceQuery = $conn->prepare("SELECT account_balance FROM users WHERE id = ?");
    $balanceQuery->bind_param("i", $user_id);
    $balanceQuery->execute();
    $balanceQuery->bind_result($balance);
    $balanceQuery->fetch();
    $balanceQuery->close();

    // Total Deposits
    $deposits = 0;
    $depositQuery = $conn->prepare("SELECT SUM(usd_amount) FROM deposits WHERE user_id = ? AND status = 'approved'");
    $depositQuery->bind_param("i", $user_id);
    $depositQuery->execute();
    $depositQuery->bind_result($deposits);
    $depositQuery->fetch();
    $deposits = $deposits ?? 0;  // ✅ Default to 0 if null
    $depositQuery->close();

    // Total Withdrawals
    $withdrawals = 0;
    $withdrawQuery = $conn->prepare("SELECT SUM(usd_amount) FROM withdrawals WHERE user_id = ? AND status = 'approved'");
    $withdrawQuery->bind_param("i", $user_id);
    $withdrawQuery->execute();
    $withdrawQuery->bind_result($withdrawals);
    $withdrawQuery->fetch();
    $withdrawals = $withdrawals ?? 0;  // ✅ Default to 0 if null
    $withdrawQuery->close();
    
    // ✅ Total Investments
    $totalInvested = 0;
    $investQuery = $conn->prepare("SELECT SUM(amount) FROM investments WHERE user_id = ? AND status = 'active'");
    $investQuery->bind_param("i", $user_id);
    $investQuery->execute();
    $investQuery->bind_result($totalInvested);
    $investQuery->fetch();
    $investQuery->close();
    
    // Total Earnings
    $totalEarnings = 0;
    $earningQuery = $conn->prepare("SELECT SUM(amount) FROM earnings WHERE user_id = ?");
    $earningQuery->bind_param("i", $user_id);
    $earningQuery->execute();
    $earningQuery->bind_result($totalEarnings);
    $earningQuery->fetch();
    $earningQuery->close();



    echo json_encode([
        'success' => true,
        'data' => [
            'balance' => $balance,
            'deposits' => $deposits,
            'withdrawals' => $withdrawals,
            'amountInvested' => $totalInvested,
            'earnings' => $totalEarnings
            // 'activeInvestments' => $activeInvestments
        ]
    ]);

?>
