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

$action = $_GET['action'] ?? '';
session_start();
$userId = $_SESSION['user_id'] ?? null;

if (!$userId) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

try {
    $db = db();
    
    if ($action === 'get_balance') {
        $stmt = $db->prepare("SELECT * FROM user_balances WHERE user_id = ?");
        $stmt->execute([$userId]);
        $balances = $stmt->fetchAll();
        echo json_encode(['success' => true, 'balances' => $balances]);
        exit;
    }

    if ($action === 'deposit') {
        $amount = (float)($_POST['amount'] ?? 0);
        $symbol = $_POST['symbol'] ?? 'USDT';

        if ($amount <= 0) throw new Exception("Invalid amount");

        $db->beginTransaction();

        // Update balance
        $stmt = $db->prepare("INSERT INTO user_balances (user_id, symbol, available) 
                              VALUES (?, ?, ?) 
                              ON DUPLICATE KEY UPDATE available = available + ?");
        $stmt->execute([$userId, $symbol, $amount, $amount]);

        // Log transaction
        $stmt = $db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status) 
                              VALUES (?, 'deposit', ?, ?, 'completed')");
        $stmt->execute([$userId, $amount, $symbol]);

        $db->commit();

        echo json_encode(['success' => true, 'message' => 'Deposit successful']);
        exit;
    }

    throw new Exception("Invalid action");

} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) $db->rollBack();
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
