<?php require_once __DIR__ . '/engine/engine.php'; ?>
<?php require_once __DIR__ . '/engine/api-handling/api_helpers.php'; ?>
<?php require_once __DIR__ . '/views/header.php'; ?>
<?php require_once __DIR__ . '/views/navigation.php'; ?>

<?php

function calculateAverageSeasonalReturns(array $historicalData, string $startDay, string $endDay): array {
	$returnsByYear = [];

	foreach ($historicalData as $entry) {
		$date = DateTime::createFromFormat('Y-m-d', $entry['date']);
		if (!$date) continue;

		$year = (int)$date->format('Y');
		$dayMonth = $date->format('d.m');

		// Sonderfall: Jahreswechsel wie "01.11" bis "31.01"
		$startTS = DateTime::createFromFormat('d.m', $startDay);
		$endTS   = DateTime::createFromFormat('d.m', $endDay);
		if (!$startTS || !$endTS) continue;

		$seasonSpansYear = $startTS > $endTS;
		$withinRange = false;

		if ($seasonSpansYear) {
			$withinRange = ($dayMonth >= $startDay || $dayMonth <= $endDay);
		} else {
			$withinRange = ($dayMonth >= $startDay && $dayMonth <= $endDay);
		}

		if ($withinRange) {
			$returnsByYear[$year][] = $entry['close'];
		}
	}

	$averageReturns = [];
	foreach ($returnsByYear as $year => $prices) {
		if (count($prices) < 2) continue;
		$start = reset($prices);
		$end = end($prices);
		$return = ($end - $start) / $start;
		$averageReturns[] = $return;
	}

	return $averageReturns;
}

function calculateCorrelation(array $x, array $y): float {
	$n = min(count($x), count($y));
	if ($n < 2) return 0.0;

	$x = array_slice($x, 0, $n);
	$y = array_slice($y, 0, $n);

	$meanX = array_sum($x) / $n;
	$meanY = array_sum($y) / $n;

	$numerator = 0;
	$denomX = 0;
	$denomY = 0;

	for ($i = 0; $i < $n; $i++) {
		$diffX = $x[$i] - $meanX;
		$diffY = $y[$i] - $meanY;
		$numerator += $diffX * $diffY;
		$denomX += $diffX ** 2;
		$denomY += $diffY ** 2;
	}

	if ($denomX == 0 || $denomY == 0) return 0.0;

	return round($numerator / sqrt($denomX * $denomY), 2);
}

$startDay = $_GET['start_day'] ?? '01.11';
$endDay   = $_GET['end_day']   ?? '31.01';

$benchmarkSymbol = '^GSPC';
$benchmarkUrl = "https://financialmodelingprep.com/api/v3/historical-price-full/{$benchmarkSymbol}?apikey={$FmpApiKey}&serietype=line";
$benchmarkJson = file_get_contents($benchmarkUrl);
$benchmarkData = json_decode($benchmarkJson, true);

$benchmarkReturns = [];
if (!empty($benchmarkData['historical'])) {
	$benchmarkReturns = calculateAverageSeasonalReturns($benchmarkData['historical'], $startDay, $endDay);
}

// Liste der zu prüfenden Aktien (z. B. aus S&P 500 JSON)
$sp500ApiUrl = "https://financialmodelingprep.com/api/v3/sp500_constituent?apikey=$FmpApiKey";
$sp500Json = file_get_contents($sp500ApiUrl);
$sp500List = json_decode($sp500Json, true);

// Fallback, falls FMP nicht liefert
if (!$sp500List || !is_array($sp500List)) {
	die('<div class="alert alert-danger">❌ Fehler beim Laden der S&P-500-Liste von FMP.</div>');
}
$results = [];

foreach (array_slice($sp500List, 0, 20) as $item) {
	$symbol = $item['symbol'];
	$url = "https://financialmodelingprep.com/api/v3/historical-price-full/{$symbol}?apikey={$FmpApiKey}&serietype=line";
	$json = file_get_contents($url);
	$data = json_decode($json, true);

	if (!empty($data['historical'])) {
		$returns = calculateAverageSeasonalReturns($data['historical'], $startDay, $endDay);

		if (count($returns) >= 3 && count($benchmarkReturns) >= 3) {
			$n = min(count($returns), count($benchmarkReturns));
			$corr = calculateCorrelation(array_slice($returns, 0, $n), array_slice($benchmarkReturns, 0, $n));
			$results[] = [
				'symbol' => $symbol,
				'correlation' => $corr,
			];
		}
	}
	usleep(250000);
}

// Sortieren nach Korrelation absteigend
usort($results, fn($a, $b) => $b['correlation'] <=> $a['correlation']);

?>
<main class="flex-grow-1">
	<div class="container pb-5">
		<h2 class="mb-4">🔍 Saisonale Korrelation mit dem S&amp;P 500 (<?= htmlspecialchars($startDay) ?>–<?= htmlspecialchars($endDay) ?>)</h2>
		<div class="d-flex flex-wrap gap-2">
			<?php foreach ($results as $res): ?>
			<?php
				$color = 'secondary';
				if ($res['correlation'] >= 0.8) $color = 'success';
				elseif ($res['correlation'] >= 0.4) $color = 'warning';
				elseif ($res['correlation'] < 0) $color = 'danger';
			?>
			<span class="badge bg-<?= $color ?>"> <?= $res['symbol'] ?>: <?= round($res['correlation'], 2) ?> </span>
			<?php endforeach; ?>
		</div>
	</div>
</main>

<?php require_once __DIR__ . '/views/footer.php'; ?>
