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

try {
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    if (!isset($_GET['account_number']) || !$_GET['account_number']) {
        throw new Exception('account_number requerido');
    }
    $accNum = trim($_GET['account_number']);

    $stmt = $pdo->prepare("SELECT * FROM trading_accounts WHERE account_number = ? AND status = 'active' LIMIT 1");
    $stmt->execute([$accNum]);
    $account = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$account) throw new Exception('Cuenta no encontrada');

    $accId = intval($account['id']);
    $balance = floatval($account['balance']);

    $pstmt = $pdo->prepare("SELECT tp.*, ti.contract_size, ti.pip_size FROM trading_positions tp LEFT JOIN trading_instruments ti ON tp.symbol = ti.symbol WHERE tp.account_id = ? AND tp.status = 'open'");
    $pstmt->execute([$accId]);
    $positions = $pstmt->fetchAll(PDO::FETCH_ASSOC);

    $finage = getFinageAPI();
    $totalMargin = 0.0;
    $totalPnl = 0.0;

    foreach ($positions as $p) {
        $symbol = $p['symbol'];
        $side = strtolower($p['type'] ?? $p['side'] ?? 'buy');
        $volume = floatval($p['volume']);
        $openPrice = floatval($p['open_price']);
        $contractSize = floatval($p['contract_size'] ?? 100000);
        $tick = $finage->getRealTimePrice($symbol);
        if (!is_array($tick)) continue;
        $bid = isset($tick['bid']) ? floatval($tick['bid']) : null;
        $ask = isset($tick['ask']) ? floatval($tick['ask']) : null;
        if (!is_numeric($bid) || !is_numeric($ask)) continue;
        $cur = ($side === 'buy') ? $bid : $ask;
        $priceDiff = ($side === 'buy') ? ($cur - $openPrice) : ($openPrice - $cur);
        $pnl = $priceDiff * $volume * $contractSize;
        $totalPnl += $pnl;
        $totalMargin += floatval($p['margin'] ?? 0.0);
    }

    $equity = $balance + $totalPnl;
    $freeMargin = $equity - $totalMargin;
    $marginLevel = $totalMargin > 0 ? (($equity / $totalMargin) * 100.0) : 0.0;

    try {
        $upd = $pdo->prepare("UPDATE trading_accounts SET equity = ?, margin = ?, free_margin = ?, margin_level = ?, updated_at = NOW() WHERE id = ?");
        $upd->execute([$equity, $totalMargin, $freeMargin, $marginLevel, $accId]);
    } catch (Throwable $e) {}

    echo json_encode([
        'success' => true,
        'kpis' => [
            'balance' => round($balance, 2),
            'equity' => round($equity, 2),
            'margin' => round($totalMargin, 2),
            'free_margin' => round($freeMargin, 2),
            'margin_level' => round($marginLevel, 2),
            'profit' => round($totalPnl, 2)
        ]
    ]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
