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

header('Content-Type: application/json');

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

if (empty($symbol)) {
	echo json_encode(['error' => 'No symbol provided']);
	exit;
}

$stmt = $pdo->prepare("
	SELECT buy_date 
	FROM depot_entries 
	WHERE symbol = :symbol 
	  AND status = 'active'
	  AND portfolio_id = :pid
	ORDER BY buy_date ASC 
	LIMIT 1
");
$stmt->execute([
	':symbol' => $symbol,
	':pid'    => $pid
]);
$buyDate = $stmt->fetchColumn();

if (!$buyDate) {
	echo json_encode(['error' => 'Buy date not found']);
	exit;
}

// --- Historische Preise via fmp_multi ---
$data = [];
try {
	if (!isset($symbol) || !$symbol) {
		throw new \RuntimeException('Symbol fehlt.');
	}

	$symbol = strtoupper(trim($symbol));

	// FMP-Daten holen
	$resp = fmp_multi([
		'history' => [
			'key'   => 'historical_price_full',
			'vars'  => ['symbol' => $symbol],
			'query' => [
				'from'      => $buyDate, // wie bisher in fetch_historical_prices_from_date()
				'serietype' => 'line',
			],
		],
	], 4);

	// Response entpacken wie bei den anderen Umstellungen
	$historyRaw = $resp['history'] ?? [];
	if (is_array($historyRaw) && isset($historyRaw['body'])) { 
		$historyRaw = $historyRaw['body']; 
	}
	if (is_array($historyRaw) && isset($historyRaw['data'])) { 
		$historyRaw = $historyRaw['data']; 
	}

	$data = is_array($historyRaw) ? $historyRaw : [];

} catch (\Throwable $ex) {
	error_log('[depot_entry_chart] FMP Fetch Error: ' . $ex->getMessage());
	$data = [];
}
// --- Ende Historische Preise ---

$prices = $data['historical'] ?? [];
if (empty($prices)) {
	echo json_encode(['error' => 'No data']);
	exit;
}

$chartData = array_reverse(array_column($prices, 'close'));

echo json_encode($chartData);