<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

$token = getAuthToken();
$user = getUserFromToken($token);

if (!$user) {
    errorResponse('Unauthorized', 401);
}

$userId = $user['id'];
$method = $_SERVER['REQUEST_METHOD'];

// Grant Admin Unrestricted Privileges: Allow admin to act on behalf of another user
if (isAdmin($user['id']) && (isset($_GET['userId']) || isset($_POST['userId']))) {
    $userId = isset($_GET['userId']) ? $_GET['userId'] : $_POST['userId'];
} elseif (isAdmin($user['id']) && $method === 'POST') {
    $jsonInput = json_decode(file_get_contents('php://input'), true);
    if (isset($jsonInput['userId'])) {
        $userId = $jsonInput['userId'];
    }
}

// Ensure table exists
$pdo->exec("CREATE TABLE IF NOT EXISTS user_assets (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id TEXT NOT NULL,
    symbol TEXT NOT NULL,
    name TEXT NOT NULL,
    balance REAL DEFAULT 0,
    color TEXT,
    icon TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(user_id, symbol)
)");

// Default assets to seed if empty
function seedDefaultAssets($pdo, $userId) {
    $defaults = [
        ['BTC', 'Bitcoin', 0.00, 'from-orange-500 to-orange-600', 'Bitcoin'],
        ['ETH', 'Ethereum', 0.00, 'from-blue-500 to-indigo-600', 'Zap'],
        ['USDT', 'Tether', 0.00, 'from-green-500 to-emerald-600', 'DollarSign'],
        ['BNB', 'Binance Coin', 0.00, 'from-yellow-400 to-yellow-600', 'Coins'],
        ['SOL', 'Solana', 0.00, 'from-purple-500 to-indigo-500', 'Ghost'],
        ['XRP', 'XRP', 0.00, 'from-blue-400 to-blue-600', 'Activity'],
        ['USDC', 'USDC', 0.00, 'from-blue-500 to-blue-700', 'DollarSign'],
        ['ADA', 'Cardano', 0.00, 'from-blue-400 to-cyan-600', 'Circle'],
        ['AVAX', 'Avalanche', 0.00, 'from-red-500 to-red-700', 'Triangle'],
        ['DOGE', 'Dogecoin', 0.00, 'from-yellow-300 to-yellow-500', 'Smile']
    ];
    
    $stmt = $pdo->prepare("INSERT OR IGNORE INTO user_assets (user_id, symbol, name, balance, color, icon) VALUES (?, ?, ?, ?, ?, ?)");
    foreach ($defaults as $asset) {
        $stmt->execute([$userId, $asset[0], $asset[1], $asset[2], $asset[3], $asset[4]]);
    }
}

if ($method === 'GET') {
    // Check if user has assets, if not seed them
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM user_assets WHERE user_id = ?");
    $stmt->execute([$userId]);
    if ($stmt->fetchColumn() == 0) {
        seedDefaultAssets($pdo, $userId);
    }

    // Fetch user's wallet address specifically to be sure
    $stmtUser = $pdo->prepare("SELECT wallet_address FROM users WHERE id = ?");
    $stmtUser->execute([$userId]);
    $walletAddress = $stmtUser->fetchColumn();

    $stmt = $pdo->prepare("SELECT * FROM user_assets WHERE user_id = ?");
    $stmt->execute([$userId]);
    $assets = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    jsonResponse(['assets' => $assets, 'address' => $walletAddress]);

} elseif ($method === 'POST') {
    $data = getJsonInput();
    
    if (!isset($data['symbol']) || !isset($data['balance'])) {
        errorResponse('Missing required fields');
    }

    $symbol = strtoupper($data['symbol']);
    $name = $data['name'] ?? $symbol;
    $balance = $data['balance'];
    $color = $data['color'] ?? 'from-gray-500 to-gray-700';
    $icon = $data['icon'] ?? 'Wallet';

    // Insert or Update
    // SQLite upsert
    $stmt = $pdo->prepare("INSERT INTO user_assets (user_id, symbol, name, balance, color, icon) VALUES (?, ?, ?, ?, ?, ?)
    ON CONFLICT(user_id, symbol) DO UPDATE SET balance = balance + excluded.balance");
    
    try {
        $stmt->execute([$userId, $symbol, $name, $balance, $color, $icon]);
        jsonResponse(['message' => 'Asset updated successfully']);
    } catch (PDOException $e) {
        errorResponse('Database error: ' . $e->getMessage());
    }
}
?>
