<?php
require_once '../config.php';
require_once '../classes/Security.php';
require_once '../classes/Wallet.php';

header('Content-Type: application/json');

// Check authentication
if (!Security::isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$action = $_POST['action'] ?? '';

switch ($action) {
    case 'add_funds':
        if (!Security::isAdmin()) {
            echo json_encode(['success' => false, 'message' => 'Admin access required']);
            exit;
        }
        
        $userId = $_POST['user_id'] ?? '';
        $cryptoId = $_POST['crypto_id'] ?? '';
        $amount = $_POST['amount'] ?? 0;
        
        if (!$userId || !$cryptoId || $amount <= 0) {
            echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
            exit;
        }
        
        $wallet = new Wallet();
        $result = $wallet->addFunds($userId, $cryptoId, $amount, 'Demo funds added by admin');
        echo json_encode($result);
        break;
        
    case 'get_balance':
        $cryptoId = $_GET['crypto_id'] ?? '';
        
        if (!$cryptoId) {
            echo json_encode(['success' => false, 'message' => 'Crypto ID required']);
            exit;
        }
        
        $wallet = new Wallet();
        $balance = $wallet->getBalance($_SESSION['user_id'], $cryptoId);
        echo json_encode(['success' => true, 'balance' => $balance]);
        break;
        
    case 'get_wallets':
        $wallet = new Wallet();
        $wallets = $wallet->getUserWallets($_SESSION['user_id']);
        echo json_encode(['success' => true, 'wallets' => $wallets]);
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>