<?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();
    $ids = [];
    if (isset($_GET['ids']) && $_GET['ids'] !== '') {
        $ids = array_filter(array_map('intval', explode(',', $_GET['ids'])), function($v){ return $v > 0; });
    } elseif (isset($_GET['client_id']) && $_GET['client_id'] !== '') {
        $ids = [intval($_GET['client_id'])];
    }
    if (!count($ids)) { throw new Exception('client_id requerido'); }

    $place = implode(',', array_fill(0, count($ids), '?'));
    $stmt = $pdo->prepare("SELECT id, client_id, account_number, balance, equity, margin, free_margin, margin_level FROM trading_accounts WHERE client_id IN ($place) AND status = 'active'");
    $stmt->execute($ids);
    $accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $byClient = [];
    foreach ($ids as $cid) { $byClient[$cid] = ['balance'=>0.0,'equity'=>0.0,'margin'=>0.0,'free_margin'=>0.0,'margin_level'=>0.0,'profit'=>0.0]; }

    $accIds = array_map(function($a){ return intval($a['id']); }, $accounts);
    $pos = [];
    if (count($accIds)) {
        $pPlace = implode(',', array_fill(0, count($accIds), '?'));
        $pstmt = $pdo->prepare("SELECT tp.account_id, tp.symbol, tp.type, tp.volume, tp.open_price FROM trading_positions tp WHERE tp.account_id IN ($pPlace) AND tp.status = 'open'");
        $pstmt->execute($accIds);
        $pos = $pstmt->fetchAll(PDO::FETCH_ASSOC);
    }

    $symbols = [];
    foreach ($pos as $p) { $s = trim($p['symbol']); if ($s) { $symbols[$s] = true; } }
    $symbols = array_keys($symbols);

    $finage = getFinageAPI();
    $prices = count($symbols) ? $finage->getMultiplePrices($symbols) : [];

    $accPnl = [];
    foreach ($pos as $p) {
        $aid = intval($p['account_id']);
        $sym = trim($p['symbol']);
        $side = strtolower($p['type'] ?? 'buy');
        $vol = floatval($p['volume']);
        $open = floatval($p['open_price']);
        $tick = $prices[$sym] ?? null;
        if (!$tick || !isset($tick['bid']) || !isset($tick['ask'])) { continue; }
        $bid = floatval($tick['bid']);
        $ask = floatval($tick['ask']);
        $cur = ($side === 'buy') ? $bid : $ask;
        $pnl = ($side === 'buy') ? (($cur - $open) * $vol * 100000) : (($open - $cur) * $vol * 100000);
        if (!isset($accPnl[$aid])) $accPnl[$aid] = 0.0;
        $accPnl[$aid] += $pnl;
    }

    $accListByClient = [];
    foreach ($accounts as $a) {
        $cid = intval($a['client_id']);
        $balance = floatval($a['balance']);
        $margin = floatval($a['margin']);
        $pnl = floatval($accPnl[intval($a['id'])] ?? 0.0);
        $equity = $balance + $pnl;
        $free = $equity - $margin;
        $ml = $margin > 0 ? (($equity / $margin) * 100.0) : 0.0;
        $byClient[$cid]['balance'] += $balance;
        $byClient[$cid]['equity'] += $equity;
        $byClient[$cid]['margin'] += $margin;
        $byClient[$cid]['free_margin'] += $free;
        $byClient[$cid]['profit'] += $pnl;
        if (!isset($accListByClient[$cid])) $accListByClient[$cid] = [];
        $accListByClient[$cid][] = [
            'account_number' => $a['account_number'],
            'balance' => round($balance, 2),
            'equity' => round($equity, 2),
            'margin' => round($margin, 2),
            'free_margin' => round($free, 2),
            'margin_level' => round($ml, 2),
            'profit' => round($pnl, 2)
        ];
    }

    foreach ($ids as $cid) {
        $m = $byClient[$cid]['margin'];
        $e = $byClient[$cid]['equity'];
        $byClient[$cid]['margin_level'] = $m > 0 ? (($e / $m) * 100.0) : 0.0;
        foreach ($byClient[$cid] as $k => $v) { $byClient[$cid][$k] = round($v, 2); }
    }

    echo json_encode(['success' => true, 'data' => $byClient, 'accounts' => $accListByClient]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
