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

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

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

	// --- Aktive Einträge laden ---
	$stmt = $pdo->prepare("
		SELECT id, symbol, shares, buy_price, asset_kind
		FROM depot_entries
		WHERE status = 'active' AND portfolio_id = :pid
	");
	$stmt->execute([':pid' => $pid]);
	$entries = $stmt->fetchAll(PDO::FETCH_ASSOC);

	if (!$entries) {
		echo json_encode([]);
		exit;
	}

	// --- Symbol-Liste normalisieren ---
	$symbols = array_values(array_unique(array_map(
		fn($r) => strtoupper(trim((string)$r['symbol'])),
		$entries
	)));

	// --- Quotes holen: erst /quote, ggf. /quote_short als Fallback ---
	$prices = [];

	$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) || !$node) return [];
		if (isset($node['body'])) $node = $node['body'];
		if (isset($node['data'])) $node = $node['data'];
		if (is_array($node) && array_key_exists(0, $node) && is_array($node[0])) return $node[0]; // /quote meist [0]
		return $node;
	};

	if ($symbols) {
		// 1) /quote
		$req = [];
		foreach ($symbols as $sym) {
			$req[$sym] = ['key' => 'quote', 'vars' => ['symbol' => $sym]];
		}
		$respQuote = fmp_multi($req, min(12, max(4, count($req))));
		$missing = [];

		foreach ($symbols as $sym) {
			$q = $unwrap($respQuote[$sym] ?? null);

			// Preis mit Fallbacks (price -> previousClose -> close)
			$price = null;
			if (isset($q['price']))           $price = (float)$q['price'];
			elseif (isset($q['previousClose'])) $price = (float)$q['previousClose'];
			elseif (isset($q['close']))         $price = (float)$q['close'];

			if ($price === null) $missing[] = $sym;

			// Datum als ISO-String 'YYYY-MM-DD'
			// /quote hat meist timestamp/ latestUpdate, sonst ggf. date
			$dateIso = null;
			$rawDate = $q['timestamp'] ?? ($q['latestUpdate'] ?? ($q['date'] ?? null));
			if (is_string($rawDate)) {
				// nur die ersten 10 Zeichen nehmen, falls ISO mit Zeit kommt
				$dateIso = substr($rawDate, 0, 10);
			} elseif (is_numeric($rawDate)) {
				$dateIso = gmdate('Y-m-d', (int)$rawDate);
			}

			$prices[$sym] = [
				'price' => $price,
				'date'  => $dateIso, // kann null sein, ist für Frontend aber optional
			];
		}

		// 2) Wo noch kein Preis: /quote_short
		if ($missing) {
			$req2 = [];
			foreach ($missing as $sym) {
				$req2[$sym] = ['key' => 'quote_short', 'vars' => ['symbol' => $sym]];
			}
			$respShort = fmp_multi($req2, min(12, max(4, count($req2))));
			foreach ($missing as $sym) {
				if (!empty($prices[$sym]['price'])) continue;
				$qs = $unwrap($respShort[$sym] ?? null);
				if (isset($qs['price'])) {
					$prices[$sym]['price'] = (float)$qs['price'];
					// date lassen wie zuvor (null ist ok)
				}
			}
		}

		// 3) Als letzte Rettung: 1-Bar-Historie (adjClose/close)
		$still = array_values(array_filter($symbols, fn($s) => empty($prices[$s]['price'])));
		if ($still) {
			$req3 = [];
			foreach ($still as $sym) {
				$req3[$sym] = [
					'key'   => 'historical_price_full',
					'vars'  => ['symbol' => $sym],
					'query' => ['timeseries' => 1, 'serietype' => 'line'],
				];
			}
			$respHist = fmp_multi($req3, min(12, max(4, count($req3))));
			foreach ($still as $sym) {
				$node = $unwrap($respHist[$sym] ?? null);
				// /historical_price_full liefert normalerweise {historical: [...]}
				$list = [];
				if (isset($node['historical']) && is_array($node['historical'])) {
					$list = $node['historical'];
				} elseif (is_array($node)) {
					$list = $node;
				}
				$first = $list[0] ?? null;
				if (is_array($first)) {
					$close = $first['adjClose'] ?? ($first['close'] ?? null);
					if ($close !== null) {
						$prices[$sym]['price'] = (float)$close;
						$prices[$sym]['date']  = isset($first['date']) ? substr((string)$first['date'], 0, 10) : ($prices[$sym]['date'] ?? null);
					}
				}
			}
		}
	}

	// --- Gesamtwert ---
	$gesamtwert = 0.0;
	foreach ($entries as $e) {
		$sym    = strtoupper(trim((string)$e['symbol']));
		$shares = (float)$e['shares'];
		$p      = $prices[$sym]['price'] ?? null;
		if ($p === null) continue;
		$gesamtwert += $p * $shares;
	}
	$gesamtwert = max(0.0, $gesamtwert);

	// --- Metriken pro Eintrag (alter Contract!) ---
	$metrics = [];
	foreach ($entries as $e) {
		$id        = (int)$e['id'];
		$sym       = strtoupper(trim((string)$e['symbol']));
		$shares    = (float)$e['shares'];
		$buyPrice  = (float)$e['buy_price'];

		$pData    = $prices[$sym] ?? null;
		$curPrice = $pData['price'] ?? null;
		$curDate  = $pData['date']  ?? null;   // 'YYYY-MM-DD' oder null

		if ($curPrice === null || $shares <= 0) continue;

		$currentValue = $curPrice * $shares;
		$buyValue     = $buyPrice * $shares;
		$perfDollar   = $currentValue - $buyValue;
		$perfPercent  = ($buyValue > 0) ? ($perfDollar / $buyValue) * 100 : 0.0;
		$gewichtung   = ($gesamtwert > 0) ? ($currentValue / $gesamtwert) * 100 : 0.0;

		$metrics[$id] = [
			'symbol'              => $sym,
			'current_price'       => round($curPrice, 2),
			'price_date'          => $curDate ? substr((string)$curDate, 0, 10) : null, // exakt wie früher: ISO-String
			'performance_dollar'  => round($perfDollar, 2),
			'performance_percent' => round($perfPercent, 2),
			'gewichtung'          => round($gewichtung, 2),
			'current_value'       => round($currentValue, 2),
		];
	}

	echo json_encode($metrics, JSON_UNESCAPED_UNICODE);
	exit;

} catch (Throwable $e) {
	file_put_contents('php://stderr', '[depot_entry_metrics] '.$e->getMessage()."\n");
	http_response_code(500);
	echo json_encode(['error' => 'server error']);
	exit;
}