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

try {
    $db = Database::getInstance();
    $pdo = $db->getConnection();

    $userId = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : 0;
    if ($userId <= 0) { throw new Exception('No autenticado'); }

    $isAdmin = false;
    try {
        $stmt = $pdo->prepare("SELECT 1 FROM user_roles ur INNER JOIN roles r ON ur.role_id = r.id WHERE ur.user_id = ? AND r.name = 'admin' LIMIT 1");
        $stmt->execute([$userId]);
        $isAdmin = (bool)$stmt->fetchColumn();
    } catch (Throwable $e) { $isAdmin = false; }
    if (!$isAdmin) { http_response_code(403); echo json_encode(['success'=>false,'message'=>'Acceso restringido']); exit; }

    $clientId = isset($_GET['client_id']) ? intval($_GET['client_id']) : 0;
    if ($clientId <= 0) { throw new Exception('client_id requerido'); }

    $stmtAcc = $pdo->prepare("SELECT id FROM trading_accounts WHERE client_id = ? AND status = 'active'");
    $stmtAcc->execute([$clientId]);
    $accIds = array_map(function($r){ return (int)$r['id']; }, $stmtAcc->fetchAll(PDO::FETCH_ASSOC));

    $positions = [];
    if (count($accIds)) {
        $place = implode(',', array_fill(0, count($accIds), '?'));
        $stmtPos = $pdo->prepare("SELECT tp.*, ti.pip_size, ti.contract_size, ti.base_currency, ti.quote_currency, ta.account_number FROM trading_positions tp LEFT JOIN trading_instruments ti ON tp.symbol = ti.symbol LEFT JOIN trading_accounts ta ON tp.account_id = ta.id WHERE tp.account_id IN ($place) AND tp.status = 'open' ORDER BY tp.opened_at DESC");
        $stmtPos->execute($accIds);
        $positions = $stmtPos->fetchAll(PDO::FETCH_ASSOC);
    }

    $finage = getFinageAPI();
    $symbols = array_values(array_unique(array_map(function($p){ return $p['symbol']; }, $positions)));
    $prices = count($symbols) ? $finage->getMultiplePrices($symbols) : [];

    $out = [];
    foreach ($positions as $p) {
        $sym = $p['symbol'];
        $type = strtolower($p['type'] ?? 'buy');
        $vol = (float)($p['volume'] ?? 0);
        $open = (float)($p['open_price'] ?? 0);
        $pipSize = isset($p['pip_size']) && is_numeric($p['pip_size']) ? (float)$p['pip_size'] : ((strpos($sym,'JPY')!==false)?0.01:0.0001);
        $contractSize = isset($p['contract_size']) ? (float)$p['contract_size'] : 100000.0;
        $tick = $prices[$sym] ?? null;
        $bid = isset($tick['bid']) ? (float)$tick['bid'] : null;
        $ask = isset($tick['ask']) ? (float)$tick['ask'] : null;
        $cur = (is_numeric($bid) && is_numeric($ask)) ? (($type==='buy') ? $bid : $ask) : (isset($tick['price']) ? (float)$tick['price'] : $open);
        $delta = ($type==='buy') ? ($cur - $open) : ($open - $cur);
        $pips = $pipSize>0 ? ($delta / $pipSize) : 0;
        $pipValuePerLotUSD = 10.0;
        $quote = $p['quote_currency'] ?? substr($sym,-3);
        if (strtoupper($quote) !== 'USD') { $pipValuePerLotUSD = ($contractSize * $pipSize) / max($cur, 1e-9); }
        $pnl = $pips * $pipValuePerLotUSD * $vol;
        $dec = (strpos($sym,'JPY')!==false)?3:5;
        $out[] = [
            'symbol' => $sym,
            'type' => $type,
            'volume' => $vol,
            'open_price' => $open,
            'current_price' => $cur,
            'pnl' => $pnl,
            'opened_at' => $p['opened_at'] ?? null,
            'account_number' => $p['account_number'] ?? null,
            'base_currency' => $p['base_currency'] ?? null,
            'quote_currency' => $p['quote_currency'] ?? null,
            'status_class' => $pnl>=0 ? 'profit' : 'loss',
            'volume_formatted' => number_format($vol, 2),
            'open_price_formatted' => number_format($open, $dec),
            'current_price_formatted' => is_numeric($cur) ? number_format($cur, $dec) : '-',
            'pnl_formatted' => (($pnl>=0?'+':'')) . number_format($pnl, 2),
            'opened_at_formatted' => isset($p['opened_at']) ? date('d/m/Y H:i', strtotime($p['opened_at'])) : '',
        ];
    }

    echo json_encode(['success'=>true,'positions'=>$out,'count'=>count($out)]);
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
?>
