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

$symbol   = $_GET['symbol']   ?? '';
$added_at = $_GET['added_at'] ?? '';

if (!$symbol || !$added_at) {
	http_response_code(400);
	exit('Ungültige Parameter');
}

$start = date('Y-m-d', strtotime($added_at));
$end   = date('Y-m-d');

// Multi-Request statt direkter URL
$resp = fmp_multi([
	'hist' => [
		'key'   => 'historical_price_full',
		'vars'  => ['symbol' => strtoupper(trim($symbol))],
		'query' => [
			'from' => $start,
			'to'   => $end
		]
	]
], 4);

// Ergebnis entpacken
$data = $resp['hist'] ?? [];
if (is_string($data)) {
	$tmp = json_decode($data, true);
	if (json_last_error() === JSON_ERROR_NONE) {
		$data = $tmp;
	}
}
if (is_object($data)) {
	$data = json_decode(json_encode($data), true);
}
if (isset($data['body'])) $data = $data['body'];
if (isset($data['data'])) $data = $data['data'];

$prices = $data['historical'] ?? [];

if (count($prices) < 2) {
	echo json_encode(['performance' => null]);
	exit;
}

// Kurse: ältester = Start, neuester = aktuell
$startPrice    = $prices[array_key_last($prices)]['close'];
$currentPrice  = $prices[0]['close'];

$perf = ($currentPrice - $startPrice) / $startPrice * 100;

echo json_encode([
	'performance'    => round($perf, 2),
	'start_date'     => $start,
	'start_price'    => round($startPrice, 2),
	'current_price'  => round($currentPrice, 2)
]);