<?php
$symbol     = $GLOBALS['tab_symbol'] ?? '';
$asof       = $GLOBALS['tab_asof'] ?? null;
$target_pe  = $GLOBALS['tab_target_pe'] ?? null;

header('Content-Type: text/html; charset=utf-8');

require_once __DIR__ . '/../../engine/bewertungsmethoden/bewertung_saisonalitaet.php';

// Steuerung (gleich wie Hauptseite)
$SEASON_SCOPE    = 'last';   // 'last' | 'weighted' | 'full'
$SEASON_YEARS    = 15;       // Default: 15 Jahre
$SEASON_HALFLIFE = 7;        // Halbwertszeit für gewichtete Methode

// Eingaben (Symbol & optional Zeitraum wie auf der Hauptseite)
$symbol   = isset($_GET['symbol']) ? strtoupper(trim($_GET['symbol'])) : ($GLOBALS['tab_symbol'] ?? '');
$startDay = $_GET['start_day'] ?? ($GLOBALS['tab_start_day'] ?? '');
$endDay   = $_GET['end_day']   ?? ($GLOBALS['tab_end_day']   ?? '');

if ($symbol === '') {
  echo '<div class="alert alert-warning mb-0">Kein Symbol übergeben.</div>';
  exit;
}

// Defaults
$avgMonthly      = array_fill(1, 12, null);
$avgDaySeries    = array_fill(0, 366, null);
$yearsOfData     = null;
$dataStartDate   = null;
$dataEndDate     = null;

$monthly         = array_fill(1, 12, []);
$monthlyStats    = [];
$monthlyBoxData  = [];
$hitRates        = [];
$heatmapRendites = [];
$heatmapHitRates = [];
$heatmapScores   = [];

$labels          = [];
$cumReturns      = [];

// Zentrale Saison-Auswertung (wie Hauptseite)
$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'] ?? null;
$dataEndDate   = $season['meta']['dataEndDate']   ?? null;
$yearsOfData   = $season['meta']['yearsOfData']   ?? null;

// Verteilung & Stats (für Heatmap/Boxplot/Ausblick)
$historicalDesc = $season['historical'] ?? [];
$monthly        = build_monthly_distribution_from_historical($historicalDesc);
$monthlyStats   = build_monthly_stats($monthly);

// Aktuelles Datum/Monat (für Linien/Annotationen)
$today             = (int)date('z');     // 0..365
$currentMonth      = (int)date('n');     // 1..12
$currentMonthIndex = $currentMonth - 1;

// Heatmap-/Boxplot-/HitRate-Daten wie Hauptseite
for ($m = 1; $m <= 12; $m++) {
  $monthlyBoxData[] = $monthly[$m] ?? [];
  if (isset($monthlyStats[$m])) {
	$s   = $monthlyStats[$m];
	$avg = (float)$s['avg'];
	$hit = (float)$s['hitRate'];

	$hitRates[]        = round($hit, 1);
	$heatmapRendites[] = round($avg, 2);
	$heatmapHitRates[] = round($hit, 1);

	// gleiche Score-/Farblogik wie Hauptseite
	$best   = $s['best'];
	$worst  = $s['worst'];
	$spread = abs($best - $worst);

	$scoreRendite    = $avg > 0 ? min(30, round($avg / 5 * 30, 1)) : 0;
	$scoreHit        = $hit >= 50 ? round(($hit - 50) / 50 * 30, 1) : 0;
	$scoreVolatility = $spread < 100 ? round((1 - min(1, $spread / 100)) * 20, 1) : 0;
	$bonus           = ($avg > 0 && $hit > 60) ? 20 : 0;

	$score = (int) round($scoreRendite + $scoreHit + $scoreVolatility + $bonus);

	// Farbmapping (gleich wie Hauptseite)
	$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 {
	$hitRates[]        = null;
	$heatmapRendites[] = 0;
	$heatmapHitRates[] = null;
	$heatmapScores[]   = 'rgba(200,200,200,0.2)';
  }
}

// --- Timeline & Kumuliert (Default: 01.01–31.12 im Format TT.MM) ---
$entryExitTimeline = [];
$labels = [];
$cumReturns = [];

$historicalDesc = $season['historical'] ?? [];

$startDay = $_GET['start_day'] ?? ($GLOBALS['tab_start_day'] ?? '');
$endDay   = $_GET['end_day']   ?? ($GLOBALS['tab_end_day']   ?? '');

// Fallbacks & Validierung wie in saisonalitaet.php (Format TT.MM)
$fmt = '/^\d{1,2}\.\d{1,2}$/';
if (!is_string($startDay) || !preg_match($fmt, $startDay)) $startDay = '01.01';
if (!is_string($endDay)   || !preg_match($fmt, $endDay))   $endDay   = '31.12';

if (!empty($historicalDesc) && function_exists('get_seasonal_segments')) {
	$segments = get_seasonal_segments($historicalDesc, $startDay, $endDay);
	if (!empty($segments)) {
		ksort($segments, SORT_NUMERIC);
		$index = 100.0;
		foreach ($segments as $year => $rows) {
			$first = reset($rows);
			$last  = end($rows);
			$startClose = $first['close'] ?? null;
			$endClose   = $last['close']  ?? null;
			if ($startClose && $endClose) {
				$ret = ($endClose - $startClose) / $startClose * 100;
				$entryExitTimeline[] = [
					'year'      => (int)$year,
					'days'      => count($rows),
					'return'    => round($ret, 2),
					'startDate' => $first['date'] ?? null,
					'endDate'   => $last['date']  ?? null,
				];
				$index *= (1 + $ret / 100);
				$labels[]     = (string)$year;
				$cumReturns[] = round($index, 2);
			}
		}
	}
}
$hasTimeline = !empty($entryExitTimeline);

$validMonthly = array_values(array_filter($avgMonthly ?? [], 'is_numeric'));
$avgLineValue = isset($avgLineValue) && $avgLineValue !== null
  ? $avgLineValue
  : (count($validMonthly) ? round(array_sum($validMonthly)/count($validMonthly), 2) : 0);
	  
$avgDaySeriesForChart = $avgDaySeries ?? [];
  if (!empty($avgDaySeriesForChart) && function_exists('smoothSeries')) {
	$avgDaySeriesForChart = smoothSeries($avgDaySeriesForChart, 5);
}

// *** ALERT: Datenhistorie (1:1 wie gewünscht) ***
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; ?>

<div class="row g-4">
	<div class="col-12">
		<div class="card">
			<div class="card-body">
				<h6 class="mb-3">Heatmap: Ø-Rendite & Trefferquote</h6>
				<div class="height-350">
					<canvas id="heatmapChart"></canvas>
				</div>
			</div>
		</div>
	</div>
	
	<div class="col-12 mt-3">
		<div class="card">
			<div class="card-body">
				<h6 class="mb-3">Saisonaler Jahresverlauf (auf Index 100 normiert)</h6>
				<div class="height-350">
					<canvas id="dailySeasonalityChart"></canvas>
				</div>
			</div>
		</div>
	</div>
	
	<div class="col-12 mt-3">
		<div class="card">
			<div class="card-body">
				<h6 class="mb-3">Durchschnittliche Monatsrenditen</h6>
				<div class="height-350">
					<canvas id="monthlyChart"></canvas>
				</div>
			</div>
		</div>
	</div>
	
	<div class="col-12 mt-3">
		<div class="card">
			<div class="card-body">
				<h6 class="mb-3">Renditeverteilung pro Monat (Boxplot)</h6>
				<div class="height-350">
					<canvas id="boxplotChart"></canvas>
				</div>
			</div>
		</div>
	</div>
	
	<div class="col-12 mt-3">
		<div class="card">
			<div class="card-body">
				<h6 class="mb-3">Trefferquote je Monat</h6>
				<div class="height-350">
					<canvas id="hitRateChart"></canvas>
				</div>
			</div>
		</div>
	</div>
	
	<?php if ($hasTimeline): ?>
		<div class="col-md-6">
			<div class="card mb-3">
				<div class="card-body">
					<div class="height-200">
						<canvas id="entryExitTimelineChart"></canvas>
					</div>
				</div>
			</div>
		</div>
		<div class="col-md-6">
			<div class="card mb-3">
				<div class="card-body">
					<div class="height-200">
						<canvas id="cumulativeChart"></canvas>
					</div>
				</div>
			</div>
		</div>
	<?php endif; ?>

</div>

<script>
// ===== PHP → JS =====
const currentMonthIndex = <?= (int)$currentMonthIndex ?>;
const todayIndex        = <?= (int)$today ?>;

const heatmapRendites   = <?= json_encode($heatmapRendites) ?>;
const heatmapHitRates   = <?= json_encode($heatmapHitRates) ?>;
const heatmapScores     = <?= json_encode($heatmapScores) ?>;

const avgDaySeries 		= <?= json_encode($avgDaySeriesForChart) ?>;

const avgMonthly        = <?= json_encode(array_values($avgMonthly ?? [])) ?>;
const avgLineValue      = <?= json_encode($avgLineValue) ?>;

const monthlyBoxData    = <?= json_encode($monthlyBoxData) ?>;

const hitRates          = <?= json_encode($hitRates) ?>;
const hitRateCounts     = <?= json_encode(array_map(fn($s)=>$s['count']??null, $monthlyStats ?? [])) ?>;

const timelineData 		= <?= json_encode($entryExitTimeline) ?>;
const cumLabels    		= <?= json_encode($labels) ?>;
const cumReturns   		= <?= json_encode($cumReturns) ?>;

const monthLbl = ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'];

// Helper: bestehende Instanz sicher zerstören
function _ctx(id) {
  var c = document.getElementById(id);
  if (!c) return null;
  if (typeof Chart !== 'undefined' && Chart.getChart) {
	var inst = Chart.getChart(c);
	if (inst) { try { inst.destroy(); } catch(e){} }
  }
  return c.getContext ? c.getContext('2d') : null;
}

function renderHeatmapChart() {
  var ctx = _ctx('heatmapChart'); if (!ctx) return;

  new Chart(ctx, {
	type: 'bar',
	data: {
	  labels: monthLbl,
	  datasets: [{
		label: 'Ø Monatsrendite (%)',
		data: heatmapRendites,
		backgroundColor: heatmapScores,
		borderWidth: 1
	  }]
	},
	options: {
	  responsive: true,
	  maintainAspectRatio: false,
	  animation: false,
	  plugins: {
		tooltip: {
		  callbacks: {
			label: function (o) {
			  var avg = (o && o.raw != null) ? o.raw : 0;
			  var hit = (heatmapHitRates && heatmapHitRates[o.dataIndex] != null)
				? heatmapHitRates[o.dataIndex] : '–';
			  return 'Ø Rendite: ' + avg.toFixed(2) + ' % | Trefferquote: ' + hit + ' %';
			}
		  }
		},
		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)'
			  }
			}
		  }
		}
	  },
	  scales: { y: { ticks: { callback: function(v){ return v + '%'; } } } }
	}
  });
}

function renderDailySeasonalityChart() {
  var ctx = _ctx('dailySeasonalityChart'); if (!ctx) return;

  var labels = []; for (var i = 1; i <= 366; i++) labels.push(i);

  new Chart(ctx, {
	type: 'line',
	data: {
	  labels: labels,
	  datasets: [{
		label: 'Indexierter Kursverlauf (Ø über Jahre)',
		data: avgDaySeries,
		borderColor: 'rgba(0, 0, 0, 0.75)',
		backgroundColor: 'rgba(0, 0, 0, 0.1)',
		fill: false,
		tension: 0.1,        // wie saisonalitaet.php
		borderWidth: 1.75,   // wie saisonalitaet.php
		pointRadius: 0
	  }]
	},
	options: {
	  responsive: true,
	  maintainAspectRatio: false,
	  animation: false,
	  plugins: {
		legend: { display: true },
		annotation: {
		  annotations: {
			today: {
			  type: 'line',
			  xMin: todayIndex,
			  xMax: todayIndex,
			  borderColor: 'red',
			  borderWidth: 1.5,
			  borderDash: [4, 4],
			  label: { enabled: true, content: 'Heute', position: 'start', backgroundColor: 'rgba(255,0,0,0.9)' }
			}
		  }
		}
	  },
	  scales: {
		x: {
		  ticks: {
			maxTicksLimit: 12,
			callback: function (value) {
			  var mi = Math.floor(value / 30.5);
			  return monthLbl[mi] || '';
			}
		  },
		  title: { display: true, text: 'Kalendertag (vereinfacht auf Monate)' } // exakt wie Vorlage
		},
		y: { title: { display: true, text: 'Index (Start = 100)' } }
	  }
	}
  });
}

function renderMonthlyChart() {
  var ctx = _ctx('monthlyChart'); if (!ctx) return;

  new Chart(ctx, {
	type: 'bar',
	data: {
	  labels: monthLbl,
	  datasets: [
		{ label: 'Ø Monatsrendite in %', data: avgMonthly, backgroundColor: 'rgba(0,0,0,1)', borderWidth: 1 },
		{ label: 'Gesamtdurchschnitt (' + avgLineValue + '%)', data: new Array(12).fill(avgLineValue),
		  type: 'line', borderColor: 'rgba(255,0,0,1)', borderWidth: 1, pointRadius: 0, tension: 0 }
	  ]
	},
	options: {
	  responsive: true,
	  maintainAspectRatio: false,
	  animation: false,
	  plugins: {
		legend: { display: true },
		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)'
			  }
			}
		  }
		}
	  },
	  scales: { y: { ticks: { callback: function(v){ return v + '%'; } } } }
	}
  });
}

function renderBoxplotChart() {
  var ctx = _ctx('boxplotChart'); if (!ctx) return;

  new Chart(ctx, {
	type: 'boxplot',
	data: {
	  labels: monthLbl,
	  datasets: [{
		label: 'Monatliche Renditen (%)',
		data: monthlyBoxData,
		backgroundColor: 'rgba(0,0,0,0.6)',
		borderColor: 'rgba(0,0,0,1)',
		borderWidth: 1
	  }]
	},
	options: {
	  responsive: true,
	  maintainAspectRatio: false,
	  plugins: {
		legend: { display: true },
		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)'
			  }
			}
		  }
		}
	  },
	  scales: { y: { ticks: { callback: function(v){ return v + '%'; } } } }
	}
  });
}

function renderHitRateChart() {
  var ctx = _ctx('hitRateChart'); if (!ctx) return;

  new Chart(ctx, {
	type: 'bar',
	data: {
	  labels: monthLbl,
	  datasets: [{ label: 'Trefferquote (%)', data: hitRates, backgroundColor: 'rgba(0,0,0,0.9)' }]
	},
	options: {
	  responsive: true,
      maintainAspectRatio: false,
	  plugins: {
		tooltip: {
		  callbacks: {
			label: function (o) {
			  var hit = (o && o.raw != null) ? o.raw : 0;
			  var n   = (hitRateCounts && hitRateCounts[o.dataIndex] != null) ? hitRateCounts[o.dataIndex] : null;
			  return n ? ('Trefferquote: ' + hit + '% (n=' + n + ')') : ('Trefferquote: ' + hit + '%');
			}
		  }
		},
		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)'
			  }
			},
			fifty: {
			  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: { min: 0, max: 100, ticks: { callback: function (v) { return v + '%'; } } } }
	}
  });
}

function renderEntryExitTimelineChart() {
  if (!timelineData || !timelineData.length) return;
  var ctx = _ctx('entryExitTimelineChart'); if (!ctx) return;

  new Chart(ctx, {
	type: 'bar',
	data: {
	  labels: timelineData.map(function (d) { return d.year; }),
	  datasets: [{
		label: 'Rendite (%)',
		data: timelineData.map(function (d) { return d.return; }),
		backgroundColor: timelineData.map(function (d) { return 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,
	  maintainAspectRatio: false,
	  scales: { y: { ticks: { callback: function (v) { return v + '%'; } } } }
	}
  });
}

function renderCumulativeChart() {
  if (!cumReturns || !cumReturns.length) return;
  var ctx = _ctx('cumulativeChart'); if (!ctx) return;

  new Chart(ctx, {
	type: 'line',
	data: {
	  labels: cumLabels,
	  datasets: [{
		label: 'Kumulierte Rendite (Index 100)',
		data: cumReturns,
		borderColor: '#000',
		backgroundColor: 'rgba(0,0,0,0)',
		borderWidth: 1.5,
		tension: 0,
		pointRadius: 0
	  }]
	},
	options: { 
		responsive: true,
		maintainAspectRatio: false,
	}
  });
}

// === Trigger (robust & einmalig) ===
let seasonalInitDone = false;

function initSeasonalCharts() {
  if (seasonalInitDone) return;
  seasonalInitDone = true;

  // Charts bauen (safe destroy via _ctx)
  renderHeatmapChart();
  renderDailySeasonalityChart();
  renderMonthlyChart();
  renderBoxplotChart();
  renderHitRateChart();
  renderEntryExitTimelineChart();
  renderCumulativeChart();
}

// 1) Direkt nach Einfügen der Tab-Datei (direkt oder via AJAX)
if (window.Chart) {
  // kleiner Tick, damit DOM sicher steht
  setTimeout(initSeasonalCharts, 0);
}

// 2) Nach Ajax-Einbindung durch den Parent
document.addEventListener('ajaxTabLoaded', (e) => {
  if (!e.detail || e.detail.targetId !== '#tab-saisonalitaet') return;
  initSeasonalCharts();
});

// 3) Reflow, wenn der Tab sichtbar wird
document.addEventListener('shown.bs.tab', function () {
  var canvases = document.querySelectorAll('#tab-saisonalitaet canvas');
  for (var i = 0; i < canvases.length; i++) {
	var inst = (window.Chart && Chart.getChart) ? Chart.getChart(canvases[i]) : null;
	if (inst) inst.resize();
  }
});
</script>