<?php
require_once __DIR__ . '/../../engine/engine.php';
require_once __DIR__ . '/../../engine/api-handling/fmp_client.php';

header('Content-Type: application/json; charset=utf-8');

try {
	$pid = isset($_GET['portfolio_id']) ? (int)$_GET['portfolio_id']
		  : (isset($_GET['pid']) ? (int)$_GET['pid'] : 1);

	$sql = "
		SELECT 
		  symbol,
		  ANY_VALUE(image)   AS image,
		  ANY_VALUE(exchange) AS exchange,
		  ANY_VALUE(isin)     AS isin,
		  SUM(shares)         AS total_shares,
		  SUM(shares * buy_price) / NULLIF(SUM(shares),0) AS avg_buy_price
		FROM depot_entries
		WHERE status = 'active'
		  AND portfolio_id = :pid
		GROUP BY symbol
		ORDER BY symbol ASC
	";
	$stmt = $pdo->prepare($sql);
	$stmt->execute([':pid' => $pid]);
	$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

	if (!$rows) {
		echo json_encode(['items' => [], 'total_current' => 0, 'as_of' => null]);
		exit;
	}

	// --- Quotes via fmp_multi (Parallel-Fetch), keine Registry nötig ---
	$symbols = array_values(array_unique(array_filter(array_map(
		static fn($s) => strtoupper(trim((string)$s)),
		$symbols ?? []
	))));
	$quotes = [];
	
	if ($symbols) {
		// 1) Requests aufbauen (ein Request je Symbol)
		$req = [];
		foreach ($symbols as $i => $sym) {
			// Wir nehmen den Key 'quote' aus fmp_client – der ruft /api/v3/quote/{symbol}
			$req[$sym] = ['key' => 'quote', 'vars' => ['symbol' => $sym]];
			// Falls du lieber quote_short magst: 'key' => 'quote_short'
		}
	
		// 2) Parallel laden (Concurrency moderat, an dein Limit anpassen)
		$concurrency = min(12, max(4, count($req)));
		$resp = fmp_multi($req, $concurrency);
	
		// 3) Unwrap-Helfer: Array[0] / Wrapper / JSON-String robust entpacken
		$unwrap = static function ($node) {
			if (is_string($node)) {
				$tmp = json_decode($node, true);
				if (json_last_error() === JSON_ERROR_NONE) { $node = $tmp; }
			}
			if (is_object($node)) { $node = json_decode(json_encode($node), true); }
			if (!is_array($node) || empty($node)) return [];
			// /quote liefert i. d. R. ein Array mit dem ersten Objekt
			if (array_key_exists(0, $node) && is_array($node[0])) return $node[0];
			// gelegentliche Wrapper
			foreach (['data','body','result','json','payload','response'] as $k) {
				if (isset($node[$k])) {
					$inner = $node[$k];
					if (is_array($inner) && array_key_exists(0, $inner) && is_array($inner[0])) return $inner[0];
					return is_array($inner) ? $inner : [];
				}
			}
			return $node; // bereits assoc
		};
	
		// 4) In das bisher genutzte $quotes-Format mappen (backwards-kompatibel)
		foreach ($symbols as $sym) {
			$q = $unwrap($resp[$sym] ?? null);
			$quotes[$sym] = [
				'symbol'    => $q['symbol']   ?? $sym,
				'price'     => isset($q['price']) ? (float)$q['price'] : null,
				'currency'  => $q['currency'] ?? ($q['Currency'] ?? null),
				'exchange'  => $q['exchange'] ?? ($q['Exchange'] ?? null),
				'timestamp' => $q['timestamp'] ?? ($q['Timestamp'] ?? null),
				// falls deine nachfolgende Logik weitere Felder braucht, kannst du sie hier 1:1 ergänzen:
				// 'previousClose' => $q['previousClose'] ?? null,
				// 'changesPercentage' => $q['changesPercentage'] ?? null,
			];
		}
	}
	// --- Ende Quotes via fmp_multi ---

	$totalCurrent = 0.0;
	$items = [];

	foreach ($rows as $r) {
		$symbol = $r['symbol'];
		$quote  = $quotes[$symbol] ?? ['price' => null, 'date' => null];
		$price  = $quote['price'];
		$shares = (float)$r['total_shares'];
		if ($price !== null && $shares > 0) {
			$totalCurrent += $price * $shares;
		}
	}

	foreach ($rows as $r) {
		$symbol   = $r['symbol'];
		$shares   = (float)$r['total_shares'];
		$avgBuy   = (float)$r['avg_buy_price'];
		$quote    = $quotes[$symbol] ?? ['price' => null, 'date' => null];
		$price    = $quote['price'];
		$dateStr  = $quote['date'];

		$currentValue = ($price !== null) ? $price * $shares : null;
		$buyValue     = $avgBuy * $shares;
		$perfUsd      = ($currentValue !== null) ? ($currentValue - $buyValue) : null;
		$perfPct      = ($currentValue !== null && $buyValue > 0) ? ($perfUsd / $buyValue * 100.0) : null;
		$weight       = ($currentValue !== null && $totalCurrent > 0) ? ($currentValue / $totalCurrent * 100.0) : null;

		$items[] = [
			'symbol'         => $symbol,
			'image'          => $r['image'],
			'exchange'       => $r['exchange'],
			'isin'           => $r['isin'],
			'shares'         => round($shares, 4),
			'avg_buy_price'  => round($avgBuy, 4),
			'current_price'  => $price !== null ? round($price, 4) : null,
			'current_value'  => $currentValue !== null ? round($currentValue, 2) : null,
			'buy_value'      => round($buyValue, 2),
			'perf_usd'       => $perfUsd !== null ? round($perfUsd, 2) : null,
			'perf_pct'       => $perfPct !== null ? round($perfPct, 2) : null,
			'weight_pct'     => $weight !== null ? round($weight, 2) : null,
			'price_date'     => $dateStr,
		];
	}

	echo json_encode([
		'items'         => $items,
		'total_current' => round($totalCurrent, 2),
		'as_of'         => null
	], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
	http_response_code(400);
	echo json_encode(['error' => $e->getMessage()]);
}
