<?php
$symbol = (string)($_GET['symbol'] ?? $_REQUEST['symbol'] ?? '');
if ($symbol === '') { echo '<div class="alert alert-warning mb-0">Kein Symbol übergeben.</div>'; return; }

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

/* 1) Nur die zwei zuverlässigen Endpoints */
$resp = fmp_multi([
  ['key' => 'earnings',                'params' => ['symbol' => $symbol]],
  ['key' => 'earning_calendar_symbol', 'params' => ['symbol' => $symbol, 'limit' => 80]],
]);

/* -------- SUPER-ROBUSTER EXTRACTOR -------- */
$is_list = function($arr){
  if (!is_array($arr)) return false;
  $keys = array_keys($arr);
  return $keys === range(0, count($arr)-1);
};

$looks_like_rows = function($arr){
  if (!$is_list($arr) || empty($arr) || !is_array($arr[0])) return false;
  // typische Felder
  $probe = array_keys($arr[0]);
  $need  = ['date','symbol']; // genügt
  foreach ($need as $n) { if (!in_array($n, $probe, true)) return false; }
  return true;
};

$extract = function($item) use ($is_list, $looks_like_rows){
  // 0) Bereits nackte Liste von Zeilen?
  if ($is_list($item) && $looks_like_rows($item)) return $item;

  // 1) Standard-Hüllen entfernen
  if (is_array($item) && array_key_exists('data',$item))         $item = $item['data'];
  elseif (is_array($item) && array_key_exists('response',$item)) $item = $item['response'];
  elseif (is_array($item) && array_key_exists('body',$item))     $item = $item['body'];
  elseif (is_array($item) && array_key_exists('payload',$item))  $item = $item['payload'];
  elseif (is_array($item) && array_key_exists('json',$item))     $item = $item['json'];

  // 2) String → JSON
  if (is_string($item)) {
	$s = trim($item);
	if ($s !== '' && ($s[0]=='{' || $s[0]=='[')) {
	  $j = json_decode($s, true);
	  if (json_last_error() === JSON_ERROR_NONE) $item = $j;
	}
  }

  // 3) erneute Standard-Hüllen lösen
  if (is_array($item) && array_key_exists('data',$item))       $item = $item['data'];
  if (is_array($item) && array_key_exists('historical',$item)) $item = $item['historical'];
  if (is_array($item) && array_key_exists('results',$item))    $item = $item['results'];

  // 4) Wenn jetzt eine nackte Liste vorliegt, zurückgeben
  if ($is_list($item)) return $item;

  // 5) Manche Clients legen den Payload unter numerischen Keys ab (z. B. [0=>[...] ...])
  if (is_array($item) && count($item) && $is_list(array_values($item))) {
	$vals = array_values($item);
	if ($is_list($vals[0]) || (is_array($vals[0]) && isset($vals[0]['date']))) return $vals[0];
  }

  return is_array($item) ? $item : [];
};

$get = function($resp, string $key, int $fallbackIdx) use ($extract){
  // a) Assoziativ?
  if (is_array($resp) && array_key_exists($key, $resp)) return $extract($resp[$key]);
  // b) Listenform mit 'key'
  if (is_array($resp)) {
	foreach ($resp as $it) {
	  if (is_array($it) && (($it['key'] ?? null) === $key)) return $extract($it);
	}
	// c) Positions-Fallback
	if (array_key_exists($fallbackIdx, $resp)) return $extract($resp[$fallbackIdx]);
  }
  return [];
};

/* --- Debug: zeige Form der Items --- */
if (is_array($resp)) {
  foreach ($resp as $idx => $it) {
	$keys = is_array($it) ? implode('|', array_keys($it)) : gettype($it);
	echo "<!-- resp[$idx]_keys=$keys -->";
  }
}

$rowsE   = [];
$rowsCal = [];

$rowsE   = (array)$get($resp, 'earnings',                0);
$rowsCal = (array)$get($resp, 'earning_calendar_symbol', 1);

/* Fallback: wenn beides leer, direkt per URL laden (um fmp_multi zu umgehen) */
if (count($rowsE) === 0 || count($rowsCal) === 0) {
  try {
	$uE  = fmp_build_url('earnings',                ['symbol'=>$symbol], []);
	$uHC = fmp_build_url('earning_calendar_symbol', ['symbol'=>$symbol,'limit'=>80], []);
	$fetch = function(string $url){
	  $ctx = stream_context_create(['http'=>['method'=>'GET','timeout'=>5,'header'=>"Accept: application/json\r\n"]]);
	  $s = @file_get_contents($url, false, $ctx);
	  if (!is_string($s) || $s === '') return [];
	  $j = json_decode($s, true);
	  return (json_last_error() === JSON_ERROR_NONE && is_array($j)) ? $j : [];
	};
	if (count($rowsE)   === 0) $rowsE   = $fetch($uE);
	if (count($rowsCal) === 0) $rowsCal = $fetch($uHC);
  } catch (\Throwable $e) {
	// schweigend weiter; Anzeige zeigt dann „Kein zukünftiger Termin“
  }
}

/* 4) Vereinheitlichen */
$unify = function(array $rows){
  $out=[];
  foreach ($rows as $r){
	$date = $r['date'] ?? ($r['reportedDate'] ?? null);
	if (!$date) continue;
	$out[] = [
	  'date'             => (string)$date,
	  'time'             => $r['time'] ?? ($r['when'] ?? null),
	  'eps'              => $r['eps'] ?? ($r['actualEps'] ?? null),
	  'epsEstimated'     => $r['epsEstimated'] ?? ($r['estimatedEps'] ?? null),
	  'revenue'          => $r['revenue'] ?? ($r['revenueActual'] ?? null),
	  'revenueEstimated' => $r['revenueEstimated'] ?? null,
	  'fiscalDateEnding' => $r['fiscalDateEnding'] ?? null,
	  'symbol'           => $r['symbol'] ?? null,
	];
  }
  return $out;
};
$E   = $unify((array)$rowsE);
$Cal = $unify((array)$rowsCal);

if (count($E) === 0 && count($Cal) === 0) {
  ?>
  <div class="row mt-3">
	<div class="col-12">
	  <div class="alert alert-warning text-center">
		Das Unternehmen <strong><?= htmlspecialchars($symbol) ?></strong> hat keine Berichtshistorie.
	  </div>
	</div>
  </div>
  <?php
  return;
}

/* 5) Future/Past bauen (wie gehabt) */
$today  = date('Y-m-d');
$future = []; $past = [];
foreach ($E as $r){ ($r['date'] >= $today) ? $future[] = $r : $past[] = $r; }
foreach ($Cal as $r){ if (($r['date'] ?? '') < $today) $past[] = $r; }

/* --- Merge pro Datum: Actuals > Estimates, Felder koaleszieren --- */
$mergeRows = function(array $rows){
  $rankTime = fn($t)=> match(strtolower((string)$t)){ 'amc'=>3,'bmo'=>2,'dmh'=>1, default=>0 };
  $best = [];
  foreach ($rows as $r){
	$d = $r['date'] ?? 'na';
	if (!isset($best[$d])) { $best[$d] = $r; continue; }
	$a = $best[$d]; $b = $r;

	$pick = function($a,$b){ return ($b !== null && $b !== '') ? $b : $a; };
	// preferiere Datensatz mit Actuals
	$preferB = (isset($b['eps']) && $b['eps'] !== null) || (isset($b['revenue']) && $b['revenue'] !== null);
	$preferA = (isset($a['eps']) && $a['eps'] !== null) || (isset($a['revenue']) && $a['revenue'] !== null);

	$winner = ($preferB && !$preferA) ? $b : (($preferA && !$preferB) ? $a : ( $rankTime($b['time']??'') > $rankTime($a['time']??'') ? $b : $a ));

	// koalesziere Felder (nehme vorhandene Werte aus beiden)
	$merged = [
	  'date'             => $winner['date'],
	  'time'             => ($rankTime($b['time']??'') > $rankTime($a['time']??'')) ? ($b['time']??null) : ($a['time']??null),
	  'eps'              => $pick($a['eps'] ?? null, $b['eps'] ?? null),
	  'epsEstimated'     => $pick($a['epsEstimated'] ?? null, $b['epsEstimated'] ?? null),
	  'revenue'          => $pick($a['revenue'] ?? null, $b['revenue'] ?? null),
	  'revenueEstimated' => $pick($a['revenueEstimated'] ?? null, $b['revenueEstimated'] ?? null),
	  'fiscalDateEnding' => $pick($a['fiscalDateEnding'] ?? null, $b['fiscalDateEnding'] ?? null),
	];
	$best[$d] = $merged;
  }
  // zurück als Liste, neu sortiert
  $out = array_values($best);
  usort($out, fn($x,$y)=> strcmp($y['date'],$x['date']));
  return $out;
};

/* Merge & Sort anwenden */
$future = $mergeRows($future);
$past   = $mergeRows($past);

/* Upcoming bestimmen und gleiches Datum aus Past entfernen */
usort($future, fn($a,$b)=> strcmp($a['date'], $b['date']));   // ASC → frühester zuerst
usort($past,   fn($a,$b)=> strcmp($b['date'], $a['date']));   // DESC → neueste zuerst

// bevorzugt Termin mit Schätzungen (epsEstimated ODER revenueEstimated), sonst erster
$futureWithEst = array_values(array_filter($future, fn($r)=>
	(isset($r['epsEstimated']) && $r['epsEstimated'] !== null)
 || (isset($r['revenueEstimated']) && $r['revenueEstimated'] !== null)
));

$upcoming = $futureWithEst[0] ?? ($future[0] ?? null);
$isUpcomingValid = is_array($upcoming) && !empty($upcoming['date']);
$uDate = $isUpcomingValid ? (string)$upcoming['date'] : null;

// gleiches Datum wie Upcoming aus Past entfernen
if ($uDate !== null) {
  $past = array_values(array_filter($past, fn($r)=> ($r['date'] ?? null) !== $uDate));
}

// Top 3 Vergangenheit
$recent3 = array_slice($past, 0, 3);

/* Debug (optional) */
echo "<!-- fallback_used=".((count($rowsE)&&count($rowsCal))?'no':'yes')
   ." earnings=".count($E)." cal_hist=".count($Cal)
   ." future=".count($future)." past=".count($past)." today=$today -->";

/* 6) Formatter */
$timeLabel = function($t){
  $t = strtolower((string)$t);
  return match ($t) { 'amc' => 'nach Börsenschluss', 'bmo' => 'vor Börsenöffnung', 'dmh' => 'am Handelstag', default => ($t!==''?strtoupper($t):'—') };
};
$dateLabel = fn($s)=> $s ? date('d.m.Y', strtotime((string)$s)) : '—';
$fmtEps = function($v){
  if ($v === null || $v === '' || !is_numeric($v)) return '—';
  $s = number_format((float)$v, 2, ',', ''); return rtrim(rtrim($s, '0'), ',');
};
$fmtRev = function($v){
  if ($v === null || $v === '' || !is_numeric($v)) return '—';
  $n=(float)$v; if (abs($n) >= 1_000_000_000) return number_format($n/1_000_000_000,1,',','').' Mrd';
  if (abs($n) >= 1_000_000) return number_format($n/1_000_000,1,',','').' Mio';
  return number_format($n,0,',','.');
};

/* === Zusatz-Formatter & Beat/Miss === */
$fmtDateShort = fn($s)=> ($s && ($t=strtotime((string)$s))) ? date('d.m.Y', $t) : '—';
$cmpBeat = function($act, $est){
  if (!is_numeric($act) || !is_numeric($est)) return null; // kein Vergleich möglich
  if ((float)$act > (float)$est) return 'beat';
  if ((float)$act < (float)$est) return 'miss';
  return 'meet';
};

/* === „Stand“ (updatedFromDate) ermitteln: nimm das jüngste Datum aus Upcoming/Future/Kalender === */
$standDates = [];
$collectStand = function($arr) use (&$standDates){
  foreach ((array)$arr as $row) {
	if (!empty($row['updatedFromDate'])) $standDates[] = (string)$row['updatedFromDate'];
  }
};
$collectStand($upcoming ? [$upcoming] : []);
$collectStand($future ?? []);
$collectStand($Cal ?? []);

$standRaw = null;
if ($standDates) {
  // Strings als Datum vergleichen
  usort($standDates, fn($a,$b)=> strcmp($b,$a)); // neuestes zuerst
  $standRaw = $standDates[0];
}

// ===== Earnings-Ampel (letzte 4 Termine) =====

// Hilfsfunktionen (nutzen deine vorhandenen Formatter, falls gewünscht)
$pickNum = fn($v)=> (is_numeric($v) ? (float)$v : null);

// Nimm $past (bei dir schon gemerged & DESC sortiert). Falls noch nicht: absichern.
$pastForScore = array_slice($past ?? [], 0, 4);

$beats = $misses = $meets = 0;
$surprises = []; // relative Überraschung in %, nur wenn schätzbar
$detail = [];    // für Tooltip

foreach ($pastForScore as $r) {
	$act = $pickNum($r['eps'] ?? null);
	$est = $pickNum($r['epsEstimated'] ?? null);

	$tag  = isset($r['date']) ? date('d.m.y', strtotime($r['date'])) : '—';
	$beatLabel = '—';
	$surpPct   = null;

	if ($act !== null && $est !== null) {
		if ($est != 0.0) {
			$surpPct = (($act - $est) / abs($est)) * 100.0;
			$surprises[] = $surpPct;
		}
		if ($act > $est) { $beats++; $beatLabel = 'Beat'; }
		elseif ($act < $est) { $misses++; $beatLabel = 'Miss'; }
		else { $meets++; $beatLabel = 'Meet'; }
	} elseif ($act !== null && $est === null) {
		// Kein Vergleich möglich, aber actual vorhanden → neutral
		$meets++;
		$beatLabel = 'n/a';
	} else {
		// gar keine EPS → ignoriere in Zählung, aber im Tooltip zeigen
		$beatLabel = '—';
	}

	$detail[] = $tag.': '.$beatLabel.(is_numeric($surpPct) ? ' ('.number_format($surpPct,1,',','')."%)" : '');
}

// Score bilden
$validN = $beats + $misses + $meets;
$avgSurprise = (count($surprises) ? array_sum($surprises)/count($surprises) : 0.0);

// Punkteregel:
// Beat = +1, Miss = -1, Meet/n/a = 0
// Bonus/Penalty für Überraschung: |surprise| > 5% => ±0.5, >10% => ±1 (pro Termin)
// Dann auf [-1..+1] normalisieren.
$pts  = ($beats * 1) + ($misses * -1); // meets = 0
$bonus = 0.0;
foreach ($surprises as $sp) {
	$abs = abs($sp);
	$delta = ($abs > 10 ? 1.0 : ($abs > 5 ? 0.5 : 0.0));
	$bonus += ($sp >= 0 ? $delta : -$delta);
}
$total = $pts + $bonus;
$norm  = ($validN > 0) ? max(-1.0, min(1.0, $total / (1.0 * max(1,$validN)))) : 0.0;

// Schwellen für Ampel
if ($validN < 2) {
	$ampel = ['label'=>'Unklar', 'class'=>'secondary'];
} else {
	if ($norm >= 0.30)      $ampel = ['label'=>'Stark',   'class'=>'success'];
	elseif ($norm >= -0.10) $ampel = ['label'=>'Gemischt', 'class'=>'warning'];
	else                    $ampel = ['label'=>'Schwach',  'class'=>'danger'];
}

// Tooltip-Text
$tt = "Beats: $beats | Misses: $misses | Meets/n.a.: $meets";
if ($validN > 0) { $tt .= " | Ø Überraschung: ".number_format($avgSurprise,1,',','')."%"; }
$tt .= " | Details: ".implode(' · ', $detail);
?>

<div class="row g-3">
	<div class="col-md-3">
		<div class="alert alert-<?= htmlspecialchars($ampel['class']) ?> mb-3" title="<?= htmlspecialchars($tt) ?>">
			<h6 class="mb-3 fw-bold">Earnings-Qualität: <?= htmlspecialchars($ampel['label']) ?></h6>
			<div class="small">
				<span class="fw-bold">Letzte <?= (int)max(0,$validN) ?>:</span><br>
				Beats: <?= (int)$beats ?> / Misses: <?= (int)$misses ?> / Meets: <?= (int)$meets ?>
			</div>
			<?php if ($validN>0): ?>
				<p class="mb-0 mt-2 fw-bold">
					Ø Überraschung: <?= number_format($avgSurprise,1,',','') ?>%
				</p>
			<?php endif; ?>
		</div>
		<div class="card">
			<div class="card-header bg-white">
				<h6 class="mb-0 fw-bold">Upcoming Earnings</h6>
				<span class="badge bg-light text-dark">
				<?php if ($isUpcomingValid): ?>
				<?php 
					$today   = new DateTime();
					$earnDay = new DateTime($uDate);
					$diff    = $today->diff($earnDay)->days;
					echo $dateLabel($uDate) . " (in {$diff} Tagen)";
				?>
				<?php else: ?>
				  —
				<?php endif; ?>
			</div>
			<div class="card-body px-0 py-2">
				<?php if ($isUpcomingValid): ?>
					<ul class="list-group list-group-flush mb-0">
						<?php if ($standRaw): ?>
							<li class="list-group-item"><strong>Stand:</strong> <?= htmlspecialchars($fmtDateShort($standRaw)) ?></li>
						<?php endif; ?>
						<?php if (array_key_exists('epsEstimated',$upcoming)): ?>
					    	<li class="list-group-item"><strong>EPS est.:</strong> <?= $fmtEps($upcoming['epsEstimated']) ?></li>
						<?php endif; ?>
						<?php if (array_key_exists('revenueEstimated',$upcoming)): ?>
					    	<li class="list-group-item"><strong>Revenue est.:</strong> <?= $fmtRev($upcoming['revenueEstimated']) ?></li>
						<?php endif; ?>
						<?php if (!empty($upcoming['fiscalDateEnding'])): ?>
					    	<li class="list-group-item"><strong>FDE:</strong> <?= htmlspecialchars((string)$upcoming['fiscalDateEnding']) ?></li>
						<?php endif; ?>
					</ul>
				<?php else: ?>
					<div class="text-muted small text-center">
						Kein zukünftiger Termin gefunden.
					</div>
				<?php endif; ?>
			</div>
		</div>
	</div>

	<?php foreach ($recent3 as $i => $r): ?>
		<?php
			$bm = $cmpBeat($r['eps'] ?? null, $r['epsEstimated'] ?? null);
			if ($bm === 'beat')      { $bmTxt = '<i class="fa fa-arrow-up-from-line"></i> Beat vs. Est.'; }
			elseif ($bm === 'miss')  { $bmTxt = '<i class="fa fa-arrow-down-from-line"></i> Miss vs. Est.'; }
			elseif ($bm === 'meet')  { $bmTxt = '<i class="fa fa-check></i> In Line'; }
			else                     { $bmTxt = null; }
		?>
		<div class="col-md-3">
			<div class="card h-100">
				<div class="card-header bg-white">
					<h6 class="mb-0 fw-bold">Letztes Earnings #<?= (int)($i+1) ?></h6>
					<small><?= $timeLabel($r['time'] ?? null) ?></small>
				</div>
				<div class="card-body px-0 py-1">
					<ul class="list-group list-group-flush mb-0">
						<li class="list-group-item">
							<strong>Datum:</strong> <?= $dateLabel($r['date'] ?? null) ?>
						</li>
						<?php if (array_key_exists('epsEstimated',$r)): ?>
							<li class="list-group-item">
								<strong>EPS:</strong> <?= $fmtEps($r['eps'] ?? null) ?> (est. <?= $fmtEps($r['epsEstimated']) ?>)
							</li>
						<?php endif; ?>
						<?php $surprisePct = (is_numeric($r['eps']) && is_numeric($r['epsEstimated']) && $r['epsEstimated'] != 0)
						  ? (($r['eps'] - $r['epsEstimated']) / abs($r['epsEstimated'])) * 100 : null;
						if ($surprisePct !== null): ?>
						  	<li class="list-group-item">
							  <strong>Surprise:</strong> <?= number_format($surprisePct,1,',','') ?>%
							</li>
						<?php endif; ?>
						<?php if (array_key_exists('revenueEstimated',$r)): ?>
							<li class="list-group-item">
								<strong>Revenue:</strong> <?= $fmtRev($r['revenue'] ?? null) ?> (est. <?= $fmtRev($r['revenueEstimated']) ?>)
							</li>
						<?php endif; ?>
						<?php if (!empty($r['fiscalDateEnding'])): ?>
							<li class="list-group-item">
								<strong>FDE:</strong> <?= htmlspecialchars((string)$r['fiscalDateEnding']) ?>
							</li>
						<?php endif; ?>
						<?php if ($bmTxt): ?>
							<li class="list-group-item"><?= $bmTxt ?></li>
						<?php endif; ?>
					</ul>
				</div>
			</div>
		</div>
	<?php endforeach; ?>
</div>

<?php
// ====== Daten für Charts vorbereiten (letzte 8 Quartale) ======
$pickNum = function($v){ return (is_numeric($v) ? (float)$v : null); };

// Wir nehmen $past (bereits gemerged) für Historie, neueste zuerst → umdrehen für chronologisch
$pastForChart = array_reverse(array_slice($past ?? [], 0, 8));

// Labels und Reihen bauen
$labels   = [];
$epsAct   = [];
$epsEst   = [];
$revAct   = [];
$revEst   = [];

foreach ($pastForChart as $r) {
  $labels[] = isset($r['date']) ? date('d.m.y', strtotime($r['date'])) : '—';
  $epsAct[] = $pickNum($r['eps'] ?? null);
  $epsEst[] = $pickNum($r['epsEstimated'] ?? null);
  $revAct[] = $pickNum($r['revenue'] ?? null);
  $revEst[] = $pickNum($r['revenueEstimated'] ?? null);
}

// Optional: Upcoming als letztes Label anhängen (nur Estimations)
if ($isUpcomingValid) {
  $labels[] = date('d.m.y', strtotime($uDate)) . '*';
  $epsAct[] = null;
  $epsEst[] = $pickNum($upcoming['epsEstimated'] ?? null);
  $revAct[] = null;
  $revEst[] = $pickNum($upcoming['revenueEstimated'] ?? null);
}

// Prüfen, ob genug Daten vorhanden sind (mind. 2 Punkte in irgendeiner Reihe)
$hasEpsSeries = (count(array_filter($epsAct, 'is_numeric')) + count(array_filter($epsEst, 'is_numeric'))) >= 2;
$hasRevSeries = (count(array_filter($revAct, 'is_numeric')) + count(array_filter($revEst, 'is_numeric'))) >= 2;
?>

<?php if ($hasEpsSeries || $hasRevSeries): ?>
	<div class="row g-3 mt-3">
		<div class="col-12">
			<h5 class="mb-1">Historische Berichte</h5>
		</div>
		<?php if ($hasEpsSeries): ?>
		<div class="col-md-6">
			<div class="card">
				<div class="card-body">
					<h6 class="mb-2">EPS – Actual vs. Estimate</h6>
					<div style="height:300px;">
						<canvas id="epsChart"></canvas>
					</div>
					<div class="text-muted small mt-1">* inkl. nächstem Termin (nur Estimations, falls verfügbar)</div>
				</div>
			</div>
		</div>
		<?php endif; ?>
	
		<?php if ($hasRevSeries): ?>
		<div class="col-md-6">
			<div class="card">
			<div class="card-body">
				<h6 class="mb-2">Revenue – Actual vs. Estimate</h6>
				<div style="height:300px;">
					<canvas id="revChart"></canvas>
				</div>
				<div class="text-muted small mt-1">* inkl. nächstem Termin (nur Estimations, falls verfügbar)</div>
			</div>
			</div>
		</div>
		<?php endif; ?>
	</div>

	<script>
		(function(){
		const labels   = <?= json_encode($labels, JSON_UNESCAPED_UNICODE) ?>;
		const epsAct   = <?= json_encode($epsAct) ?>;
		const epsEst   = <?= json_encode($epsEst) ?>;
		const revAct   = <?= json_encode($revAct) ?>;
		const revEst   = <?= json_encode($revEst) ?>;
	
		const nf = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 2 });
	
		function mkLineChart(ctx, title, labels, datasets, valueFormatter){
			new Chart(ctx, {
			type: 'line',
			data: { labels, datasets },
			options: {
				responsive: true,
				maintainAspectRatio: false,
				interaction: { 
					mode: 'index',
					intersect: false 
				},
				plugins: {
				legend: { 
					position: 'top'
				},
				tooltip: {
					callbacks: {
						label: (context) => {
							const v = context.parsed.y;
							const nm = context.dataset.label || '';
							return nm + ': ' + (v == null ? '—' : valueFormatter(v));
						}
					}
				},
				title: { display: false }
			},
			elements: {
				point: {
					radius: 3
				}, 
				line: {
					tension: 0.2
				}
			},
			spanGaps: true,
				scales: {
					x: { 
						ticks: { autoSkip: true },
						grid: { display: false }
					},
					y: {
						ticks: {
						callback: (val) => valueFormatter(val)
						}
					}
				}
			}
			});
		}
	
		// EPS-Chart
		<?php if ($hasEpsSeries): ?>
		mkLineChart(
			document.getElementById('epsChart').getContext('2d'),
			'EPS',
			labels,
			[
				{ label: 'EPS (Actual)', data: epsAct, borderColor: 'black', borderWidth: 2, spanGaps: true },
				{ label: 'EPS (Estimate)', data: epsEst, borderColor: 'red', borderWidth: 2, borderDash: [6,4], spanGaps: true }
			],
			(v)=> nf.format(v)
		);
		<?php endif; ?>
	
		// Revenue-Chart – Achse in Mrd/Mio formatieren
		<?php if ($hasRevSeries): ?>
		const fmtRevenue = (v) => {
			const n = Number(v);
			if (!isFinite(n)) return '—';
			if (Math.abs(n) >= 1_000_000_000) return nf.format(n/1_000_000_000) + ' Mrd';
			if (Math.abs(n) >= 1_000_000)     return nf.format(n/1_000_000)     + ' Mio';
			return nf.format(n);
		};
		mkLineChart(
			document.getElementById('revChart').getContext('2d'),
			'Revenue',
			labels,
			[
			{ label: 'Revenue (Actual)', data: revAct,  borderColor: 'black', borderWidth: 2, spanGaps: true },
			{ label: 'Revenue (Estimate)', data: revEst, borderColor: 'red', borderWidth: 2, borderDash: [6,4], spanGaps: true }
			],
			fmtRevenue
		);
		<?php endif; ?>
		})();
	</script>
<?php endif; ?>

