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

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

$user_id = $_SESSION['user_id'];

// Get account balance
$stmt = $conn->prepare("SELECT account_balance FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$balanceResult = $stmt->get_result();
$balance = $balanceResult->fetch_assoc()['account_balance'] ?? 0.0;

// Get total investments
$stmt = $conn->prepare("SELECT SUM(amount) AS total_invested FROM investments WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$investResult = $stmt->get_result();
$total_invested = $investResult->fetch_assoc()['total_invested'] ?? 0.0;

// Get total withdrawals (approved only)
$stmt = $conn->prepare("SELECT SUM(usd_amount) AS total_withdrawn FROM withdrawals WHERE user_id = ? AND status = 'approved'");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$withdrawResult = $stmt->get_result();
$total_withdrawn = $withdrawResult->fetch_assoc()['total_withdrawn'] ?? 0.0;

// Recent wallet activities (last 6 entries from deposits, withdrawals, investments combined)
$activities = [];
$sql = "
    SELECT 'Deposit' AS type, usd_amount, status, created_at FROM deposits WHERE user_id = ?
    UNION ALL
    SELECT CONCAT('Investment - ', package_name), amount, 'active' AS status, start_date AS created_at FROM investments WHERE user_id = ?
    UNION ALL
    SELECT 'Withdrawal', usd_amount, status, created_at FROM withdrawals WHERE user_id = ?
    ORDER BY created_at DESC LIMIT 6
";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iii", $user_id, $user_id, $user_id);
$stmt->execute();
$activitiesResult = $stmt->get_result();
while ($row = $activitiesResult->fetch_assoc()) {
    $activities[] = $row;
}

// Response
echo json_encode([
    'success' => true,
    'data' => [
        'balance' => number_format($balance, 2),
        'invested' => number_format($total_invested, 2),
        'withdrawn' => number_format($total_withdrawn, 2),
        'activities' => $activities
    ]
]);
