<?php
/**
 * Get User Details API
 * Returns user information and wallet balances as JSON
 */

require_once '../config/database.php';
require_once '../includes/functions.php';

// Check if admin is logged in
session_start();
if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$conn = getConnection();
$userId = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($userId <= 0) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid user ID']);
    exit;
}

// Get user details
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    http_response_code(404);
    echo json_encode(['error' => 'User not found']);
    exit;
}

// Get country details for currency
$countryQuery = $conn->prepare("SELECT currency_symbol FROM countries WHERE name = ?");
$countryQuery->bind_param("s", $user['country']);
$countryQuery->execute();
$countryResult = $countryQuery->get_result()->fetch_assoc();
$currencySymbol = $countryResult['currency_symbol'] ?? 'KSH';

// Get wallet balances from wallets table
$wallets = [];
$walletTypes = ['referral', 'task', 'video', 'trivia', 'ads', 'bonus', 'spin', 'blog', 'meme'];

foreach ($walletTypes as $type) {
    $walletQuery = $conn->prepare("
        SELECT 
            COALESCE(main_wallet, 0) as main_wallet,
            COALESCE(referral_wallet, 0) as referral_wallet,
            COALESCE(video_wallet, 0) as video_wallet,
            COALESCE(trivia_wallet, 0) as trivia_wallet,
            COALESCE(ads_wallet, 0) as ads_wallet,
            COALESCE(bonus_wallet, 0) as bonus_wallet,
            COALESCE(spin_wallet, 0) as spin_wallet,
            COALESCE(blog_wallet, 0) as blog_wallet,
            COALESCE(meme_wallet, 0) as meme_wallet
        FROM wallets 
        WHERE user_id = ? AND type = ?
        LIMIT 1
    ");
    $walletQuery->bind_param("is", $userId, $type);
    $walletQuery->execute();
    $result = $walletQuery->get_result()->fetch_assoc();
    
    if ($result) {
        // Store the wallet amount for this type
        $columnName = $type . '_wallet';
        $wallets[$type] = floatval($result[$columnName] ?? 0);
    }
}

// If wallets are empty, get from the first row (they're duplicated across all types)
if (empty($wallets) || array_sum($wallets) == 0) {
    $firstWalletQuery = $conn->prepare("
        SELECT 
            COALESCE(main_wallet, 0) as main_wallet,
            COALESCE(referral_wallet, 0) as referral_wallet,
            COALESCE(video_wallet, 0) as video_wallet,
            COALESCE(trivia_wallet, 0) as trivia_wallet,
            COALESCE(ads_wallet, 0) as ads_wallet,
            COALESCE(bonus_wallet, 0) as bonus_wallet,
            COALESCE(spin_wallet, 0) as spin_wallet,
            COALESCE(blog_wallet, 0) as blog_wallet,
            COALESCE(meme_wallet, 0) as meme_wallet
        FROM wallets 
        WHERE user_id = ?
        LIMIT 1
    ");
    $firstWalletQuery->bind_param("i", $userId);
    $firstWalletQuery->execute();
    $firstWallet = $firstWalletQuery->get_result()->fetch_assoc();
    
    if ($firstWallet) {
        $wallets = [
            'referral' => floatval($firstWallet['referral_wallet']),
            'task' => floatval($firstWallet['main_wallet']), // main_wallet is task wallet
            'video' => floatval($firstWallet['video_wallet']),
            'trivia' => floatval($firstWallet['trivia_wallet']),
            'ads' => floatval($firstWallet['ads_wallet']),
            'bonus' => floatval($firstWallet['bonus_wallet']),
            'spin' => floatval($firstWallet['spin_wallet'] ?? 0),
            'blog' => floatval($firstWallet['blog_wallet'] ?? 0),
            'meme' => floatval($firstWallet['meme_wallet'] ?? 0)
        ];
    }
}

// Calculate total balance
$totalBalance = array_sum($wallets);

// Prepare response
$response = [
    'success' => true,
    'user_id' => $user['id'],
    'username' => $user['username'],
    'email' => $user['email'],
    'phone' => $user['phone'],
    'country' => $user['country'],
    'status' => $user['status'],
    'referral_code' => $user['referral_code'] ?? 'N/A',
    'referred_by' => $user['referred_by'],
    'currency_symbol' => $currencySymbol,
    'wallets' => $wallets,
    'total_balance' => number_format($totalBalance, 2)
];

// Return JSON response
header('Content-Type: application/json');
echo json_encode($response);
?>