<?php
require_once __DIR__ . '/engine/engine.php';
require_once __DIR__ . '/engine/api-handling/api_helpers.php';
require_once __DIR__ . '/engine/api-handling/api_helpers_multi_fetch.php';
require_once __DIR__ . '/engine/api-handling/fmp_client.php';
require_once __DIR__ . '/engine/bewertungsmethoden/bewertung_saisonalitaet.php';

$requires_search = true;
$requires_chartjs = true;

require_once __DIR__ . '/views/header.php';
require_once __DIR__ . '/views/navigation.php';

// Einstellungen
$SEASON_SCOPE    = 'last';   // 'last' | 'weighted' | 'full'
$SEASON_YEARS    = 15;       // Default: 15 Jahre
$SEASON_HALFLIFE = 7;        // nur für 'weighted'

$symbol         = null;
$companyName    = null;
$startDay       = $_GET['start_day'] ?? '';
$endDay         = $_GET['end_day'] ?? '';

$avgMonthly     = array_fill(1, 12, null);
$avgDaySeries   = array_fill(0, 366, null);
$segments       = [];
$yearsOfData    = null;
$dataStartDate  = null;
$dataEndDate    = null;

$monthly        = array_fill(1, 12, []);
$monthlyStats   = [];
$monthlyCombinedScores = [];
$monthlyScores  = [];

if (!isset($labels))     $labels = [];
if (!isset($cumReturns)) $cumReturns = [];

if (!empty($_GET['symbol'])) {
	$symbol  = strtoupper($_GET['symbol']);

	// Profil (optional)
	$multi = fmp_multi([
		'profile' => [
			'key'  => 'profile',
			'vars' => ['symbol' => $symbol],
		],
	]);
	$profile = is_array($multi['profile'] ?? null) ? ($multi['profile'][0] ?? []) : [];
	
	if (!empty($profile['companyName'])) {
		$companyName = $profile['companyName'];
	}

	// zentrale Saison-Auswertung
	$season = compute_seasonality($symbol, [
		'scope'      => $SEASON_SCOPE,
		'years'      => $SEASON_YEARS,
		'half_life'  => $SEASON_HALFLIFE,
	]);

	// Mapping
	$avgMonthly     = $season['avgMonthly'];
	$avgDaySeries   = $season['avgDaySeries'];
	$dataStartDate  = $season['meta']['dataStartDate'];
	$dataEndDate    = $season['meta']['dataEndDate'];
	$yearsOfData    = $season['meta']['yearsOfData'];

	// Monatsverteilung & Stats (für Heatmap/Boxplot/Ausblick)
	$historicalDesc = $season['historical'] ?? [];
	$monthly        = build_monthly_distribution_from_historical($historicalDesc);
	$monthlyStats   = build_monthly_stats($monthly);
	
	// Aktuelles Datum/Monat
	$today              = (int)date('z');
	$currentMonth       = (int)date('n');
	$currentMonthIndex  = $currentMonth - 1;
	
	// Empfehlung + Score für aktuellen Monat
	$recommendationText  = null;
	$recommendationLevel = null;
	$recColor            = 'secondary';
	$monthlyScore        = null;
	
	if (isset($monthlyStats[$currentMonth])) {
		$s = $monthlyStats[$currentMonth];
		// Score nach deiner Formel
		$best   = $s['best'];
		$worst  = $s['worst'];
		$spread = abs($best - $worst);
	
		$scoreRendite    = $s['avg'] > 0 ? min(30, round($s['avg'] / 5 * 30, 1)) : 0;
		$scoreHit        = $s['hitRate'] >= 50 ? round(($s['hitRate'] - 50) / 50 * 30, 1) : 0;
		$scoreVolatility = $spread < 100 ? round((1 - min(1, $spread / 100)) * 20, 1) : 0;
		$bonus           = ($s['avg'] > 0 && $s['hitRate'] > 60) ? 20 : 0;
	
		$monthlyScore = (int) round($scoreRendite + $scoreHit + $scoreVolatility + $bonus);
		
		// Badge-/Progress-Farbe
		if (!function_exists('getScoreColor')) {
			function getScoreColor($score) {
				if ($score >= 80) return 'bg-success';
				if ($score >= 60) return 'bg-secondary';
				if ($score >= 40) return 'bg-warning';
				return 'bg-danger';
			}
		}
		$scoreColor = !is_null($monthlyScore) ? getScoreColor($monthlyScore) : 'bg-secondary';
	
		// Empfehlungstext
		if ($s['hitRate'] >= 70 && $s['avg'] > 1) {
			$recommendationText  = 'Historisch starker Monat mit guter Trefferquote.';
			$recommendationLevel = 'Positiv';
			$recColor            = 'success';
		} elseif ($s['hitRate'] >= 50 && $s['avg'] > 0) {
			$recommendationText  = 'Leicht positive Tendenz, aber mit Unsicherheit.';
			$recommendationLevel = 'Neutral bis leicht positiv';
			$recColor            = 'warning';
		} elseif ($s['avg'] < 0 && $s['hitRate'] < 50) {
			$recommendationText  = 'Vorsicht – historisch schwacher Monat mit negativer Bilanz.';
			$recommendationLevel = 'Negativ';
			$recColor            = 'danger';
		} else {
			$recommendationText  = 'Durchschnittlicher Verlauf ohne klare Tendenz.';
			$recommendationLevel = 'Neutral';
			$recColor            = 'secondary';
		}
	}
	
	// Badge-Farbe Funktion (für die Tabelle)
	if (!function_exists('getScoreColor')) {
		function getScoreColor($score) {
			if ($score >= 80) return 'bg-success';
			if ($score >= 60) return 'bg-secondary';
			if ($score >= 40) return 'bg-warning';
			return 'bg-danger';
		}
	}
	
	// Ausblick: nächste 3 Monate
	$monthlyScores = [];
	for ($i = 0; $i < 3; $i++) {
		$m = (($currentMonth + $i - 1) % 12) + 1; // 1..12
		if (isset($monthlyStats[$m])) {
			$s = $monthlyStats[$m];
			$best   = $s['best'];
			$worst  = $s['worst'];
			$spread = abs($best - $worst);
	
			$scoreRendite    = $s['avg'] > 0 ? min(30, round($s['avg'] / 5 * 30, 1)) : 0;
			$scoreHit        = $s['hitRate'] >= 50 ? round(($s['hitRate'] - 50) / 50 * 30, 1) : 0;
			$scoreVolatility = $spread < 100 ? round((1 - min(1, $spread / 100)) * 20, 1) : 0;
			$bonus           = ($s['avg'] > 0 && $s['hitRate'] > 60) ? 20 : 0;
	
			$monthlyScores[$m] = [
				'score'   => (int) round($scoreRendite + $scoreHit + $scoreVolatility + $bonus),
				'avg'     => $s['avg'],
				'hitRate' => $s['hitRate'],
			];
		}
	}
	
	// Für Tabellen/Charts unten
	$monthlyCombinedScores = [];
	foreach ($monthlyStats as $m => $s) {
		$monthlyCombinedScores[$m] = ($s['avg'] * 10) + $s['hitRate'];
	}
	$maxScoreMonth = !empty($monthlyCombinedScores) ? array_keys($monthlyCombinedScores, max($monthlyCombinedScores))[0] : null;
	$minScoreMonth = !empty($monthlyCombinedScores) ? array_keys($monthlyCombinedScores, min($monthlyCombinedScores))[0] : null;
	
	// Boxplot/Heatmap-Hilfsarrays
	$monthlyBoxData = [];
	for ($m = 1; $m <= 12; $m++) {
		$monthlyBoxData[] = $monthly[$m] ?? [];
	}
	$hitRates = [];
	foreach ($monthlyStats as $m => $s) {
		$hitRates[] = $s['hitRate'];
	}
	
	// Heatmap-Rohdaten (Rendite & Farbe)
	$heatmapRendites = [];
	$heatmapHitRates = [];
	$heatmapScores   = [];
	for ($m = 1; $m <= 12; $m++) {
		if (isset($monthlyStats[$m])) {
			$avg   = $monthlyStats[$m]['avg'];
			$hit   = $monthlyStats[$m]['hitRate'];
			$heatmapRendites[] = round($avg, 2);
			$heatmapHitRates[] = round($hit, 1);
			$scoreRendite = max(0, min(50, ($avg * 10)));
			$scoreHit     = max(0, min(50, ($hit - 40) * 1.25));
			$score        = round($scoreRendite + $scoreHit);
			$heatmapScores[] = ($score >= 80) ? 'rgba(0, 150, 0, 0.7)'
							 : (($score >= 60) ? 'rgba(100, 180, 0, 0.7)'
							 : (($score >= 40) ? 'rgba(255, 200, 0, 0.7)'
							 : (($score >= 20) ? 'rgba(255, 120, 0, 0.7)'
											   : 'rgba(220, 50, 50, 0.7)')));
		} else {
			$heatmapRendites[] = 0;
			$heatmapHitRates[] = null;
			$heatmapScores[]   = 'rgba(200,200,200,0.2)';
		}
	}
	
	// --- Minimal helper: median() (no logic changes elsewhere) ---
	if (!function_exists('median')) {
		/**
		 * @param array $values Numeric array
		 * @return float Median of values
		 */
		function median(array $values) {
			if (empty($values)) {
				return 0.0;
			}
			sort($values, SORT_NUMERIC);
			$n = count($values);
			$mid = intdiv($n, 2);
			if ($n % 2 === 1) {
				return (float) $values[$mid];
			}
			return ($values[$mid - 1] + $values[$mid]) / 2;
		}
	}
	// --- end helper ---
}

?>

<main class="flex-grow-1">
	<div class="container pb-5">
		<?php
		if (!empty($startDay) && !empty($endDay) && !empty($symbol) && !empty($season['historical'])) {
		$segments = get_seasonal_segments($season['historical'], $startDay, $endDay);
			
			$entryExitTimeline = [];
			foreach ($segments as $year => $rows) {
				$first = reset($rows);
				$last  = end($rows);
				$startDate = $first['date'];
				$endDate   = $last['date'];
				$startClose = $first['close'];
				$endClose = $last['close'];
			
				if ($startClose > 0) {
					$return = ($endClose - $startClose) / $startClose * 100;
					$entryExitTimeline[] = [
						'year' => $year,
						'days' => count($rows),
						'return' => round($return, 2),
						'startDate' => $startDate,
						'endDate' => $endDate,
					];
				}
			}
		}
		?>
		<div class="mt-5 d-flex justify-content-between">
			<h2 class="mb-0 d-inline-block">
				Saisonale Analyse:
				<?php if ($companyName): ?>
					<?= htmlspecialchars($companyName) ?> (<?= htmlspecialchars($symbol) ?>)
				<?php elseif ($symbol): ?>
					<?= htmlspecialchars($symbol) ?>
				<?php endif; ?>
			</h2>
			<div>
			<?php
				if ($symbol) {
					$category = 'Saisonalität';
					include 'execute/watchlist/watchlist_button.php';
				}
			?>
			</div>
		</div>
		<div class="sticky-top bg-white z-3 pb-1 pt-3 sticky-offset">
			<form method="GET" class="row g-3 mb-4 align-items-end">
				<div class="col-md-3">
					<label for="symbol" class="form-label">Symbol eingeben:</label>
					<input type="text" class="form-control symbol-autocomplete" name="symbol" id="symbol" placeholder="AAPL" value="<?= htmlspecialchars($symbol ?? '') ?>" required>
				</div>
				<div class="col-md-3">
					<label for="start_day" class="form-label">Start (TT.MM)</label>
					<input type="text" class="form-control" name="start_day" id="start_day" placeholder="TT.MM" value="<?= htmlspecialchars($_GET['start_day'] ?? '') ?>">
				</div>
				<div class="col-md-3">
					<label for="end_day" class="form-label">Ende (TT.MM)</label>
					<input type="text" class="form-control" name="end_day" id="end_day" placeholder="TT.MM" value="<?= htmlspecialchars($_GET['end_day'] ?? '') ?>">
				</div>
				<div class="col-md-3">
					<button type="submit" class="btn btn-dark w-100">Analysieren</button>
				</div>
			</form>
		</div>
		
		<?php if (isset($yearsOfData, $dataStartDate, $dataEndDate)): ?>
			<div class="alert alert-light text-dark mb-4 py-2">
				Kursdaten verfügbar von <strong><?= (new DateTime($dataStartDate))->format('d.m.Y') ?></strong>
				bis <strong><?= (new DateTime($dataEndDate))->format('d.m.Y') ?></strong>
				(≈ <strong><?= $yearsOfData ?> Jahre</strong> saisonale Datenbasis)
			</div>
		<?php endif; ?>
		
		<?php if ($symbol): ?>	
			<div class="row align-items-stretch">
				<div class="col-md-6 d-flex">
					<?php if (!empty($recommendationText)): ?>
						<div class="card mb-4 w-100">
							<div class="card-body d-flex flex-column">	
								<div class="alert alert-<?= $recColor ?> mb-3">
									<h5 class="mb-1">Empfehlung für <?= DateTime::createFromFormat('!m', $currentMonth)->format('F') ?>:</h5>
									<strong><?= $recommendationLevel ?>:</strong> <?= $recommendationText ?>
								</div>
								<?php if (!is_null($monthlyScore)): ?>
									<div class="mt-2">
										<h6 class="mb-1">Monatsscore für <?= DateTime::createFromFormat('!m', $currentMonth)->format('F') ?>:</h6>
										<div class="progress" style="height: 24px;">
											<div class="progress-bar <?= $scoreColor ?>" role="progressbar" style="width: <?= $monthlyScore ?>%;" aria-valuenow="<?= $monthlyScore ?>" aria-valuemin="0" aria-valuemax="100">
												<strong><?= $monthlyScore ?>/100</strong>
											</div>
										</div>
									</div>
								<?php endif; ?>
							</div>
						</div>
					<?php endif; ?>
				</div>
				<div class="col-md-6 d-flex">
					<?php if (!empty($monthlyScores)): ?>
						<div class="card mb-4 w-100">
							<div class="card-body d-flex flex-column">	
								<h6 class="mb-3">Saisonaler Ausblick (nächste 3 Monate):</h6>
								<div class="table-responsive">
									<table class="table table-sm table-bordered w-100 mb-0">
										<thead class="table-light">
											<tr>
												<th>Monat</th>
												<th>Ø Rendite</th>
												<th>Trefferquote</th>
												<th>Score</th>
											</tr>
										</thead>
										<tbody>
											<?php foreach ($monthlyScores as $month => $data): ?>
											<tr>
												<td><strong><?= DateTime::createFromFormat('!m', $month)->format('F') ?></strong></td>
												<td><?= number_format($data['avg'], 2) ?> %</td>
												<td><?= number_format($data['hitRate'], 1) ?> %</td>
												<td>
													<span class="badge <?= getScoreColor($data['score']) ?>"><?= $data['score'] ?>/100</span>
												</td>
											</tr>
											<?php endforeach; ?>
										</tbody>
									</table>
								</div>
							</div>
						</div>
					<?php endif; ?>
				</div>
			</div>
			
			<?php
				if (!empty($segments)) {
				$avgReturn = calc_avg_return($segments);
				$hitRatio  = calc_hit_ratio($segments);
				$maxDD     = calc_max_drawdown($segments);
				$volatility = calc_volatility($segments);
				$entryExit = get_best_entry_exit_day($segments);
				$sim = simulate_trades($segments);
				
				$returns = [];
				$cumReturns = [];
				$labels = [];
				$index = 100;
				$totalDays = 0;
				
				ksort($segments);
				foreach ($segments as $year => $rows) {
					$start = $rows[0]['close'] ?? null;
					$end = end($rows)['close'] ?? null;
					if ($start && $end) {
						$return = ($end - $start) / $start * 100;
						$returns[] = $return;
						$totalDays += count($rows);
						$index *= (1 + $return / 100);
						$cumReturns[] = round($index, 2);
						$labels[] = $year;
					}
				}
				
				$medianReturn = !empty($returns) ? round(median($returns), 2) : 0;
				$hitRatio2 = !empty($returns) ? round(count(array_filter($returns, fn($r) => $r > 0)) / count($returns) * 100, 1) : 0;
				$cumulativeReturn = !empty($returns) ? round((array_product(array_map(fn($r) => (1 + $r / 100), $returns)) - 1) * 100, 2) : 0;
				
				$years = count($returns);
				$annualizedReturn = $years > 1 ? round((pow(1 + $cumulativeReturn / 100, 1 / $years) - 1) * 100, 2) : 0;
				
				$positiveYears = count(array_filter($returns, fn($r) => $r > 0));
				$totalYears = count($returns);
				
				$count = count($returns);
				$avg = $count > 0 ? array_sum($returns) / $count : 0;
				$stddev = $count > 0 ? sqrt(array_sum(array_map(fn($r) => pow($r - $avg, 2), $returns)) / $count) : 0;
				$sharpe = $stddev > 0 ? round($avg / $stddev, 2) : 0;
				
				$gains = array_filter($returns, fn($r) => $r > 0);
				$losses = array_filter($returns, fn($r) => $r < 0);
				
				$avgGain = !empty($gains) ? round(array_sum($gains) / count($gains), 2) : 0;
				$avgLoss = !empty($losses) ? round(array_sum($losses) / count($losses), 2) : 0;
				
				$maxGain = !empty($returns) ? round(max($returns), 2) : 0;
				$maxLoss = !empty($returns) ? round(min($returns), 2) : 0;
				$avgDays = $count > 0 ? round($totalDays / $count) : 0;
					
				$annualizedReturn = $avgDays > 0 ? round((pow(1 + $avgReturn / 100, 365 / $avgDays) - 1) * 100, 2) : 0;
				$monthlyEquivalent = round($annualizedReturn / 12, 2);
				$annualizedColor = $annualizedReturn >= 0 ? 'success' : 'danger';
			?>
			<div class="d-flex justify-content-between">
			<h5 class="mb-0">Performance im Zeitraum:</h5>
			<span class="badge bg-info text-white w-auto align-self-start"><?= htmlspecialchars($startDay) ?> bis <?= htmlspecialchars($endDay) ?></span>
			</div>
			<div class="row mt-3 mb-2">
				<div class="col-md-3 d-flex">
					<div class="card mb-4 w-100">
						<div class="card-body d-flex flex-column">
							<h6 class="mb-2">Trefferquote:</h6>
							<div class="progress mt-1 mb-3" style="height: 8px;">
								<div class="progress-bar bg-black" role="progressbar" style="width: <?= $hitRatio ?>%;" aria-valuenow="<?= $hitRatio ?>" aria-valuemin="0" aria-valuemax="100"></div>
							</div>
							<h3><strong><?= $hitRatio ?>%</strong></h3>
							<div class="alert alert-<?= $annualizedColor ?> text-dark mt-2">
								<h6>Annualisierter Gewinn:</h6>
								<h1><strong><?= $annualizedReturn ?>%</strong></h1>
								<small class="text-muted">(Ø <?= $monthlyEquivalent ?> %/Monat)</small>
							</div>
							Kumulative Rendite:
							<h5><strong><?= $cumulativeReturn ?>%</strong></h5>
						</div>
					</div>
				</div>
				<div class="col-md-3 d-flex">
					<div class="card mb-4 w-100">
						<div class="card-body d-flex flex-column">
							<h6 class="mb-2">Durchschnittliche Monatsrenditen:</h6>
							<ul class="list-group list-group-flush mt-2">
								<li class="list-group-item px-0">⌀ Rendite: <strong><?= $avgReturn ?>%</strong></li>
								<li class="list-group-item px-0">Medianrendite: <strong><?= $medianReturn ?>%</strong></li>
								<li class="list-group-item px-0">Max. Drawdown: <strong><?= $maxDD ?>%</strong></li>
								<li class="list-group-item px-0">Volatilität: <strong><?= $volatility ?>%</strong></li>
								<li class="list-group-item px-0">Jahre mit Gewinn: <strong><?= $positiveYears ?>/<?= $totalYears ?></strong></li>
							</ul>
						</div>
					</div>
				</div>
				<div class="col-md-3 d-flex">
					<div class="card mb-4 w-100">
						<div class="card-body d-flex flex-column">
							<h6 class="mb-2">Performance Details:</h6>
							<ul class="list-group list-group-flush mt-2">
								<li class="list-group-item px-0">Durchschnittliche Länge: <strong><?= $avgDays ?> Tage</strong></li>
								<li class="list-group-item px-0">Ø Gewinn: <strong><?= $avgGain ?>%</strong></li>
								<li class="list-group-item px-0">Ø Verlust: <strong><?= $avgLoss ?>%</strong></li>
								<li class="list-group-item px-0">Max. Gewinn: <strong><?= $maxGain ?>%</strong></li>
								<li class="list-group-item px-0">Max. Verlust: <strong><?= $maxLoss ?>%</strong></li>
								<li class="list-group-item px-0">Standardabweichung: <strong><?= round($stddev, 2) ?>%</strong></li>
								<li class="list-group-item px-0">Sharpe Ratio: <strong><?= $sharpe ?></strong></li>
							</ul>
						</div>
					</div>
				</div>
				<div class="col-md-3 d-flex">
					<div class="card mb-4 w-100">
						<div class="card-body d-flex flex-column text-center">
							<h6 class="mb-3">Bester Einstieg/Ausstieg:</h6>
							<div class="alert alert-warning text-dark">
								<h5 class="mb-0">
								<strong>
									<?php
									$period = explode(' - ', $entryExit['period']);
									$startFormatted = DateTime::createFromFormat('Y-m-d', $period[0]);
									$endFormatted   = DateTime::createFromFormat('Y-m-d', $period[1]);
									
									if ($startFormatted && $endFormatted) {
										echo $startFormatted->format('d.m.') . ' bis ' . $endFormatted->format('d.m.');
									} else {
										echo htmlspecialchars($entryExit['period']);
									}
									?>
								</strong>
								</h5>
							</div>
							<h5 class="mt-2">Ø Rendite: <strong><?= $entryExit['avgReturn'] ?> %</strong></h5>
							<ul class="list-group list-group-flush mt-5 text-start">
								<li class="list-group-item px-0">Long (Buy zu Start, Sell zu Ende): <strong><?= $sim['longAvg'] ?> %</strong></li>
								<li class="list-group-item px-0">Short (Sell zu Start, Buy zu Ende): <strong><?= $sim['shortAvg'] ?> %</strong></li>
							</ul>
						</div>
					</div>
				</div>
				<div class="col-md-6">
					<div class="card mb-4">
						<div class="card-body">
							<canvas id="entryExitTimelineChart" height="160"></canvas>
						</div>
					</div>
				</div>
				<div class="col-md-6">
					<div class="card mb-4">
						<div class="card-body">
							<canvas id="cumulativeChart" height="160"></canvas>
						</div>
					</div>
				</div>
			</div>
			
			<?php
			} elseif (!empty($startDay) && !empty($endDay)) {
				echo '<div class="alert alert-warning">Keine vollständigen Zeiträume zwischen ' .
					htmlspecialchars($startDay) . ' und ' . htmlspecialchars($endDay) . ' in den Kursdaten gefunden.</div>';
			}
			?>
	
			<div class="row mt-2 mb-3">
				<div class="col-12">
					<div class="card mb-3">
						<div class="card-body">
							<h6>Heatmap: Ø-Rendite & Trefferquote</h6>
							<canvas id="heatmapChart" height="90"></canvas>
						</div>
					</div>
					<?php if (!empty(array_filter($avgMonthly, fn($v)=>is_numeric($v)) )): ?>
						<div class="card mb-3">
							<div class="card-body">
								<h6>Durchschnittlicher Jahresverlauf (täglich):</h6>
								<canvas id="dailySeasonalityChart" height="90"></canvas>
							</div>
						</div>
						
						<div class="card mb-3">
							<div class="card-body">
								<h6>Durchschnittliche Monatsrenditen:</h6>
								<canvas id="monthlyChart" height="90"></canvas>
							</div>
						</div>

						<div class="card mb-3">
							<div class="card-body">
								<h6>Renditeverteilung pro Monat:</h6>
								<canvas id="boxplotChart" height="90"></canvas>
							</div>
						</div>
						
						<div class="card">
							<div class="card-body">
								<h6>Trefferquoten je Monat:</h6>
								<canvas id="hitRateChart" height="90"></canvas>
							</div>
						</div>
					<?php else: ?>
						<div class="alert alert-warning">Keine historischen Daten für <strong><?= htmlspecialchars($symbol) ?></strong> gefunden.</div>
					<?php endif; ?>
				</div>
			</div>
			
			<div class="row mb-3 mt-4">
				<div class="col-12">
					<h5 class="mb-3">Statistiken:</h5>
					<div class="table-responsive">
						<table class="table table-sm">
							<thead class="table-dark">
								<tr>
								<th>Monat</th>
								<th>Ø Rendite</th>
								<th>Beste</th>
								<th>Schlechteste</th>
								<th>Trefferquote</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ($monthlyStats as $m => $s): 
									$rowClass = '';
								
									if ($m == $maxScoreMonth) {
										$rowClass = 'table-success'; // bester Monat
									} elseif ($m == $minScoreMonth) {
										$rowClass = 'table-danger'; // schlechtester Monat
									}
								?>
								<tr class="<?= $rowClass ?>">
								<td><strong><?= DateTime::createFromFormat('!m', $m)->format('M') ?></strong></td>
								<td><strong><?= $s['avg'] ?> %</strong></td>
								<td><?= $s['best'] ?> %</td>
								<td><?= $s['worst'] ?> %</td>
								<td><strong><?= $s['hitRate'] ?> %</strong></td>
								</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>
				</div>
			</div>
			
		<?php endif; ?>
	</div>
</main>

<?php if ($symbol): ?>
	<?php if (!empty($avgMonthly)): ?>
		<?php		
			$avgLineValue = null;
			if (!empty($avgMonthly)) {
				$valid = array_filter($avgMonthly, fn($v) => is_numeric($v));
				$avgLineValue = (count($valid) > 0) 
					? round(array_sum($valid) / count($valid), 2) 
					: 0;
			}
		?>
	<script>
	const monthlyChart = new Chart(document.getElementById('monthlyChart'), {
		type: 'bar',
		data: {
			labels: ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
			datasets: [
			{
				label: 'Ø Monatsrendite in %',
				data: <?= json_encode(array_values($avgMonthly)) ?>,
				backgroundColor: 'rgba(0, 0, 0, 1)',
				borderColor: 'rgba(0, 0, 0, 1)',
				borderWidth: 1
			},
			{
				label: 'Gesamtdurchschnitt (<?= $avgLineValue ?>%)',
				data: Array(12).fill(<?= $avgLineValue ?>),
				type: 'line',
				borderColor: 'rgba(255, 0, 0, 1)',
				borderWidth: 1,
				pointRadius: 0,
				fill: false
			}
			]
		},
		options: {
			responsive: true,
			plugins: {
				title: {
					display: true,
					text: 'Durchschnittliche Monatsrenditen (basierend auf mehreren Jahren)',
					color: '#000'
				},
				tooltip: {
					callbacks: {
						label: ctx => `${ctx.raw.toFixed(2)} %`
					}
				},
				annotation: {
				annotations: {
					todayMonthLine: {
					type: 'line',
					xMin: <?= $currentMonthIndex ?>,
					xMax: <?= $currentMonthIndex ?>,
					borderColor: 'red',
					borderWidth: 1.5,
					borderDash: [4, 4],
					label: {
						content: 'Aktueller Monat',
						enabled: true,
						position: 'start',
						backgroundColor: 'rgba(255,0,0,0.9)'
					}
					}
				}
				}
			},
			scales: {
				y: {
					ticks: {
						callback: val => val + '%'
					}
				}
			}
		}
	});
	</script>
	<?php endif; ?>
	
	<?php if (!empty($avgDaySeries)): ?>
	<?php
		$avgDaySeries = smoothSeries($avgDaySeries, 5);
	?>
	<script>
	const dailyChart = new Chart(document.getElementById('dailySeasonalityChart'), {
		type: 'line',
		data: {
			labels: Array.from({ length: 366 }, (_, i) => i + 1),
			datasets: [{
				label: 'Indexierter Kursverlauf (Ø über Jahre)',
				data: <?= json_encode($avgDaySeries) ?>,
				borderColor: 'rgba(0, 0, 0, 0.75)',
				backgroundColor: 'rgba(0, 0, 0, 0.1)',
				fill: false,
				tension: 0.1,
				borderWidth: 1.75,
				pointRadius: 0
			}]
		},
		options: {
			responsive: true,
			plugins: {
				title: {
					display: true,
					text: 'Saisonaler Jahresverlauf (auf Index 100 normiert)',
					color: '#000'
				},
				tooltip: {
					callbacks: {
						label: function(ctx) {
							const dayOfYear = ctx.dataIndex + 1;
				
							// Hilfsfunktion für Datum aus Kalendertag
							const date = new Date(2020, 0); // beliebiges Schaltjahr
							date.setDate(dayOfYear);
				
							const options = { day: 'numeric', month: 'long' };
							const dateStr = date.toLocaleDateString('de-DE', options);
				
							return `${dateStr} – Index: ${ctx.raw.toFixed(2)}`;
						}
					}
				},
				annotation: {
					annotations: {
					todayLine: {
						type: 'line',
						xMin: <?= $today ?>,
						xMax: <?= $today ?>,
						borderColor: 'red',
						borderWidth: 1.5,
						borderDash: [4, 4],
						label: {
						content: 'Heute',
						enabled: true,
						position: 'start',
						backgroundColor: 'rgba(255,0,0,0.9)'
						}
					}
					}
				}
			},
			scales: {
				x: {
					ticks: {
						callback: function(value, index, ticks) {
							const monthLabels = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'];
							const day = value;
							const monthIndex = Math.floor(day / 30.5); // grobe Zuordnung
							return monthLabels[monthIndex] ?? '';
						},
						maxTicksLimit: 12
					},
					title: { display: true, text: 'Kalendertag (vereinfacht auf Monate)' }
				},
				y: {
					title: { display: true, text: 'Index (Start = 100)' }
				}
			}
		}
	});
	</script>
	<?php endif; ?>
	
	<?php if (!empty($monthlyBoxData)): ?>
	<script>
	const boxplotChart = new Chart(document.getElementById('boxplotChart'), {
		type: 'boxplot',
		data: {
			labels: ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
			datasets: [{
				label: 'Monatliche Renditen (%)',
				data: <?= json_encode($monthlyBoxData) ?>,
				backgroundColor: 'rgba(0, 0, 0, 0.6)',
				borderColor: 'rgba(0, 0, 0, 1)',
				borderWidth: 1
			}]
		},
		options: {
			responsive: true,
			plugins: {
				title: {
					display: true,
					text: 'Boxplot: Verteilung der Monatsrenditen',
					color: '#000'
				},
				tooltip: {
					callbacks: {
						label: ctx => {
						const v = ctx.raw;
						if (!v || typeof v.min !== 'number') {
							return 'Keine Daten';
						}
						return `Min: ${v.min.toFixed(2)}%, Q1: ${v.q1.toFixed(2)}%, Median: ${v.median.toFixed(2)}%, Q3: ${v.q3.toFixed(2)}%, Max: ${v.max.toFixed(2)}%`;
						}
					}
				},
				annotation: {
				annotations: {
					todayMonthLine: {
					type: 'line',
					xMin: <?= $currentMonthIndex ?>,
					xMax: <?= $currentMonthIndex ?>,
					borderColor: 'rgba(255,0,0,0.25)',
					borderWidth: 1.5,
					borderDash: [4, 4],
					label: {
						content: 'Aktueller Monat',
						enabled: true,
						position: 'start',
						backgroundColor: 'rgba(255,0,0,0.9)'
					}
					}
				}
				}
			},
			scales: {
				y: {
					title: {
						display: true,
						text: 'Rendite (%)'
					},
					ticks: {
						callback: val => val + '%'
					}
				}
			}
		}
	});
	</script>
	<?php endif; ?>
	
	<?php if (!empty($hitRates)): ?>
		<?php
			$hitRateCounts = [];
			foreach ($monthlyStats as $month => $s) {
				$hitRateCounts[] = $s['count'];
			}
		?>
	<script>
	const hitRateCounts = <?= json_encode($hitRateCounts) ?>;
	const hitRateChart = new Chart(document.getElementById('hitRateChart'), {
	type: 'bar',
	data: {
		labels: ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
		datasets: [{
		label: 'Trefferquote (%)',
		data: <?= json_encode($hitRates) ?>,
		backgroundColor: 'rgba(0, 0, 0, 0.9)'
		}]
	},
	options: {
		responsive: true,
		plugins: {
		title: {
			display: true,
			text: 'Wie oft war der Monat positiv?',
			color: '#000'
		},
		tooltip: {
			callbacks: {
				label: function(ctx) {
				const hit = ctx.raw;
				const count = hitRateCounts[ctx.dataIndex] ?? 0;
				return `${hit.toFixed(1)} % (${count} Monate)`;
				}
			}
		},
		annotation: {
		  annotations: {
			currentMonth: {
			  type: 'line',
			  xMin: <?= $currentMonthIndex ?>, xMax: <?= $currentMonthIndex ?>,
			  borderColor: 'rgba(255,0,0,0.6)', borderWidth: 1.5, borderDash: [4,4],
			  label: { enabled: true, content: 'Akt. Monat', position: 'start', backgroundColor: 'rgba(255,0,0,0.9)' }
			},
			fiftyLine: {
			  type: 'line',
			  yMin: 50, yMax: 50,
			  borderColor: 'rgba(0,0,0,0.35)', borderWidth: 1, borderDash: [6,6],
			  label: { enabled: true, content: '50 %', backgroundColor: 'rgba(255,255,255,0.8)', color:'#000', position:'center' }
			}
		  }
		}
		},
		scales: {
		y: {
			ticks: {
			callback: val => val + '%'
			},
			min: 0,
			max: 100
		}
		}
	}
	});
	</script>
	<?php endif; ?>
	
	<?php if (!empty($heatmapRendites)): ?>
	<script>
	const heatmapHitRatesJS = <?= json_encode($heatmapHitRates) ?>;
	
	const heatmapChart = new Chart(document.getElementById('heatmapChart'), {
	type: 'bar',
	data: {
		labels: ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
		datasets: [{
		label: 'Ø Monatsrendite (%)',
		data: <?= json_encode($heatmapRendites) ?>,
		backgroundColor: <?= json_encode($heatmapScores) ?>,
		borderWidth: 1
		}]
	},
	options: {
		responsive: true,
		plugins: {
		title: { display: true, text: 'Kombinierte Bewertung: Rendite + Trefferquote', color: '#000' },
		tooltip: {
			callbacks: {
			label: function(ctx) {
				const avg = ctx.raw;
				const hit = heatmapHitRatesJS[ctx.dataIndex];
				return `Ø Rendite: ${avg.toFixed(2)} % | Trefferquote: ${hit ?? '–'} %`;
			}
			}
		},
		annotation: {
			annotations: {
			todayMonthLine: {
				type: 'line',
				xMin: <?= $currentMonthIndex ?>,
				xMax: <?= $currentMonthIndex ?>,
				borderColor: 'red',
				borderWidth: 1.5,
				borderDash: [4, 4],
				label: { content: 'Aktueller Monat', enabled: true, position: 'start', backgroundColor: 'rgba(255,0,0,0.9)' }
			}
			}
		}
		},
		scales: { y: { ticks: { callback: val => val + '%' } } }
	}
	});
	</script>
	<?php endif; ?>
	
	<?php if (!empty($entryExitTimeline)): ?>
	<script>
	const timelineData = <?= json_encode(array_reverse($entryExitTimeline)) ?>;
	const timelineChart = new Chart(document.getElementById('entryExitTimelineChart'), {
		type: 'bar',
		data: {
			labels: timelineData.map(d => d.year),
			datasets: [{
				label: 'Rendite (%)',
				data: timelineData.map(d => d.return),
				backgroundColor: timelineData.map(d => d.return >= 0 ? 'rgba(0, 128, 0, 0.7)' : 'rgba(200, 0, 0, 0.7)'),
				borderColor: 'rgba(0, 0, 0, 0.9)',
				borderWidth: 0
			}]
		},
		options: {
			responsive: true,
			plugins: {
				title: {
					display: true,
					text: 'Bester saisonaler Zeitraum pro Jahr (Realrendite)',
					color: '#000'
				},
				tooltip: {
					callbacks: {
						label: function(ctx) {
							const d = timelineData[ctx.dataIndex];
							const dir = d.return >= 0 ? 'Long' : 'Short';
							return `${dir}-Trade: ${d.startDate} bis ${d.endDate}, ${d.return.toFixed(2)} %`;
						}
					}
				}
			},
			scales: {
				y: {
					ticks: {
						callback: val => val + '%'
					}
				}
			}
		}
	});
	</script>
	<?php endif; ?>
	
	<?php if (!empty($_GET['start_day']) && !empty($_GET['end_day'])): ?>
	<script>
	const ctx = document.getElementById('cumulativeChart').getContext('2d');
	new Chart(ctx, {
		type: 'line',
		data: {
			labels: <?= json_encode($labels) ?>,
			data: <?= json_encode($cumReturns) ?>,
			datasets: [{
				label: 'Kumulierte Rendite (Index 100)',
				data: <?= json_encode($cumReturns) ?>,
				borderColor: '#000',
				backgroundColor: 'rgba(0,0,0,0)',
				borderWidth: 1.5,
				tension: 0,
				pointRadius: 0,
				pointHoverRadius: 3
			}]
		},
		options: {
			plugins: {
				title: {
					display: true,
					text: 'Kumulierte Rendite (Index 100)',
					color: '#000'
				},
				tooltip: {
					mode: 'index',
					intersect: false,
					callbacks: {
						label: function(context) {
							return context.dataset.label + ': ' + context.formattedValue + '%';
						}
					}
				}
			},
			scales: {
				y: {
					ticks: {
						callback: function(value) {
							return value + '%';
						}
					}
				},
				x: {
					reverse: false
				}
			}
		}
	});
	</script>
	<?php endif; ?>
<?php endif; ?>

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