<?php
$symbol = $GLOBALS['tab_symbol'] ?? ($_GET['symbol'] ?? '');
require_once __DIR__ . '/../../engine/api-handling/fmp_client.php';
require_once __DIR__ . '/../../engine/bewertungsmethoden/bewertung_korrelationen.php';

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

$corrData = bewertung_korrelationen_run($symbol);

if (!empty($corrData['error'])) {
  echo '<div class="alert alert-danger mb-0">'.htmlspecialchars($corrData['error']).'</div>';
  return;
}

// Helper
$sectorLabel = $corrData['meta']['sector'] ?? null;
$sectorEtf   = $corrData['meta']['sector_etf'] ?? null;
$leadlag     = $corrData['leadlag'] ?? null;
$risk        = $corrData['risk'] ?? null;

$wA = (string)($corrData['windows'][0] ?? 30);
$wB = (string)($corrData['windows'][1] ?? 90);
$wC = (string)($corrData['windows'][2] ?? 252);
$wShow = $wC;
$beta  = $risk['beta'][$wShow] ?? null;
$volA  = $risk['vol']['asset'][$wShow] ?? null;
$volM  = $risk['vol']['spy'][$wShow] ?? null;
$rel   = $risk['vol']['rel'][$wShow] ?? null;

$fmt = function($v, $d=2) { return ($v===null ? '—' : number_format((float)$v, $d, ',', '.')); };

// ETF-Beschreibungen für Erklärungsspalte
$ETF_INFO = [
  'SPY' => 'SPDR S&P 500 ETF (US-Large Caps)',
  'QQQ' => 'Invesco QQQ (NASDAQ-100)',
  'IWM' => 'iShares Russell 2000 (Small Caps)',
  'EWG' => 'iShares MSCI Germany (Deutschland)',
  'FEZ' => 'SPDR EURO STOXX 50 (Eurozone Blue Chips)',
  'EFA' => 'iShares MSCI EAFE (Developed ex-US/Canada)',
  'EEM' => 'iShares MSCI Emerging Markets',
  'TLT' => 'iShares 20+ Year Treasury Bond',
  'HYG' => 'iShares iBoxx $ High Yield Corporate Bond',
  'UUP' => 'Invesco DB US Dollar Index Bullish',
  'GLD' => 'SPDR Gold Shares',
  'USO' => 'United States Oil Fund',
  'VIXY'=> 'ProShares VIX Short-Term Futures',
  'XLC' => 'Communication Services Select Sector SPDR',
  'XLY' => 'Consumer Discretionary Select Sector SPDR',
  'XLP' => 'Consumer Staples Select Sector SPDR',
  'XLE' => 'Energy Select Sector SPDR',
  'XLF' => 'Financial Select Sector SPDR',
  'XLV' => 'Health Care Select Sector SPDR',
  'XLI' => 'Industrial Select Sector SPDR',
  'XLK' => 'Technology Select Sector SPDR',
  'XLB' => 'Materials Select Sector SPDR',
  'XLRE'=> 'Real Estate Select Sector SPDR',
  'XLU' => 'Utilities Select Sector SPDR',
];

?>

<div class="row">
	<div class="col-12">
		<div class="d-flex align-items-center justify-content-between">
			<h5 class="card-title mb-0">Korrelationen für <?= htmlspecialchars($corrData['symbol']) ?></h5>
			<div>
				<?php if ($sectorLabel || $sectorEtf): ?>
					<?php if ($sectorLabel): ?>
						<span class="badge bg-light text-muted me-2">Sektor: <?= htmlspecialchars($sectorLabel) ?></span>
					<?php endif; ?>
					<?php if ($sectorEtf): ?>
						<span class="badge bg-light text-muted">Sektor-ETF: <?= htmlspecialchars($sectorEtf) ?></span>
					<?php endif; ?>
				<?php endif; ?>
			</div>
		</div>
	</div>
</div>

<?php if ($risk): ?>
	<div class="row g-3 mt-1 mb-3">
		<div class="col-6 col-md-3">
			<div class="card">
				<div class="card-body py-2">
					<div class="text-muted small">Beta (<?= (int)$wShow ?>d)</div>
					<div class="fw-bold fs-5"><?= $fmt($beta, 2) ?></div>
				</div>
			</div>
		</div>
		<div class="col-6 col-md-3">
			<div class="card">
				<div class="card-body py-2">
					<div class="text-muted small">Vola Aktie (ann.)</div>
					<div class="fw-bold fs-5"><?= $fmt($volA, 2) ?>%</div>
				</div>
			</div>
		</div>
		<div class="col-6 col-md-3">
			<div class="card">
				<div class="card-body py-2">
					<div class="text-muted small">Vola SPY (ann.)</div>
					<div class="fw-bold fs-5"><?= $fmt($volM, 2) ?>%</div>
				</div>
			</div>
		</div>
		<div class="col-6 col-md-3">
			<div class="card">
				<div class="card-body py-2">
					<div class="text-muted small">Rel. Vola (A/SPY)</div>
					<div class="fw-bold fs-5"><?= $fmt($rel, 2) ?></div>
				</div>
			</div>
		</div>
	</div>
<?php endif; ?>

<?php if ($leadlag): ?>
	<div class="row mb-2 mt-2">
		<div class="col-12">
			<?php if ($leadlag && isset($leadlag['bestCorr'])): 
				$lag = (int)$leadlag['bestLag'];
				$corr= (float)$leadlag['bestCorr'];
				$hint = $lag === 0
					? "läuft synchron zum Markt"
					: ($lag > 0 ? "folgt dem Markt um {$lag} Tage" : "führt den Markt um " . abs($lag) . " Tage");
			?>
				<div class="alert alert-light border d-flex align-items-center py-2">
					<div class="me-2">Lead/Lag vs. SPY (±<?= (int)$leadlag['maxLag'] ?>):</div>
					<div><strong><?= $hint ?></strong> (max |Korr| bei Lag <?= $lag ?>: <?= number_format($corr, 2) ?>)</div>
				</div>
			<?php endif; ?>
		</div>
	</div>
<?php endif; ?>

<div class="row">
	<div class="col-12">
		<div class="card">
			<div class="card-body">
				<h6>Benchmark-Korrelationen</h6>
				<canvas id="corrBarTab" height="80"></canvas>
				<div class="table-responsive mt-4">
					<table class="table align-middle" id="corrTableTab">
						<thead class="table-dark">
							<tr>
								<th>Benchmark</th>
								<th>Erklärung</th>
								<th><?= (int)$wA ?>d</th>
								<th><?= (int)$wB ?>d</th>
								<th><?= (int)$wC ?>d</th>
							</tr>
						</thead>
						<tbody>
							<?php
							// Sortierung wie auf der Seite: nach 90d desc
							$rows = $corrData['benchmarks'] ?? [];
							usort($rows, function($a,$b) use($wB){
								$av = $a['corr'][$wB] ?? -9999;
								$bv = $b['corr'][$wB] ?? -9999;
								if ($av === null) $av = -9999;
								if ($bv === null) $bv = -9999;
								return $bv <=> $av;
							});
							foreach ($rows as $r):
								$sym = $r['symbol'] ?? '';
								$info = $ETF_INFO[$sym] ?? ('Benchmark: '.$sym);
							?>
							<tr>
								<td><?= htmlspecialchars($sym) ?></td>
								<td><?= htmlspecialchars($info) ?></td>
								<td><?= $fmt($r['corr'][$wA] ?? null) ?></td>
								<td><?= $fmt($r['corr'][$wB] ?? null) ?></td>
								<td><?= $fmt($r['corr'][$wC] ?? null) ?></td>
							</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</div>

<div class="row mt-3">
	<div class="col-12">
		<div class="card">
			<div class="card-body">
				<h6>Rolling 90-Tage Korrelation zum S&P500</h6>
				<canvas id="corrRollingTab" height="90" class="mt-2"></canvas>
			</div>
		</div>
	</div>
</div>

<script>
(function(){
  const data   = <?= json_encode($corrData, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
  const ETFMAP = <?= json_encode($ETF_INFO, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
  const winA = String(data.windows?.[0] ?? '30');
  const winB = String(data.windows?.[1] ?? '90');
  const winC = String(data.windows?.[2] ?? '252');
  function fmt(v){ return (v===null || isNaN(v)) ? '—' : Number(v).toFixed(2); }

  // DataTables optional – wie auf der Seite (gleiche IDs/Styles, nur andere ID)
  if (window.jQuery && jQuery.fn && jQuery.fn.DataTable && !jQuery.fn.dataTable.isDataTable('#corrTableTab')) {
	jQuery('#corrTableTab').DataTable({ paging:false, searching:false, info:false, order: [] });
  }

  // Bar-Chart (90d) schwarz, ohne Grid – gleiche Optik wie Seite
  if (window.Chart) {
	const rows = (data.benchmarks || []).slice().sort((a,b)=>{
	  const av = a.corr?.[winB]; const bv = b.corr?.[winB];
	  const ax = (av===null||isNaN(av)) ? -999 : av;
	  const bx = (bv===null||isNaN(bv)) ? -999 : bv;
	  return bx - ax;
	});
	const labels = rows.map(r=> r.symbol);
	const vals90 = rows.map(r=> r.corr?.[winB]);
	if (window._corrBarTab) window._corrBarTab.destroy();
	const ctxBar = document.getElementById('corrBarTab').getContext('2d');
	window._corrBarTab = new Chart(ctxBar, {
	  type: 'bar',
	  data: {
		labels,
		datasets: [{
		  label: `${winB}-Tage Korrelation zu ${data.symbol}`,
		  data: vals90,
		  backgroundColor: 'black',
		  borderColor: 'black'
		}]
	  },
	  options: {
		responsive: true,
		scales: {
		  x: { ticks: { color: 'black' } },
		  y: { min: -1, max: 1, ticks: { color: 'black' } }
		},
		plugins: {
		  tooltip: {
			callbacks: {
			  title: (items)=> {
				const sym = items?.[0]?.label || '';
				return `${sym} — ${ETFMAP[sym] || 'Benchmark'}`;
			  },
			  label: (ctx)=> `${ctx.dataset.label}: ${fmt(ctx.raw)}`
			}
		  },
		  legend: { labels: { color: 'black' } }
		}
	  }
	});
  }

  // Rolling (90d) vs SPY – ohne Grid/Labels, Linien bei 0/±0.4/±0.7
  if (window.Chart) {
	const roll = data.rolling || [];
	const labelsR = roll.map(d=> d.date);
	const valsR   = roll.map(d=> d.corr);

	if (window._corrRollingTab) window._corrRollingTab.destroy();
	const ctxRoll = document.getElementById('corrRollingTab').getContext('2d');
	window._corrRollingTab = new Chart(ctxRoll, {
	  type: 'line',
	  data: {
		labels: labelsR,
		datasets: [{
		  label: `Rolling 90-Tage Korr. (${data.symbol} vs SPY)`,
		  data: valsR,
		  borderColor: 'black',
		  backgroundColor: 'black',
		  pointRadius: 0,
		  tension: 0.3,
		  borderWidth: 1.5
		}]
	  },
	  options: {
		responsive: true,
		scales: {
		  x: { ticks: { display: false }, grid: { display: false } },
		  y: { min: -1, max: 1, ticks: { color: 'black' }, grid: { display: false } }
		},
		plugins: {
		  tooltip: { callbacks: { label: (ctx)=> `${ctx.dataset.label}: ${fmt(ctx.raw)}` } },
		  legend: { labels: { color: 'black' } },
		  annotation: {
			annotations: {
			  zeroLine: { type: 'line', yMin: 0,   yMax: 0,   borderColor: 'red',   borderWidth: 1, borderDash: [6,6] },
			  pos04:    { type: 'line', yMin: 0.4, yMax: 0.4, borderColor: 'black', borderWidth: 1, borderDash: [4,4] },
			  neg04:    { type: 'line', yMin:-0.4, yMax:-0.4, borderColor: 'black', borderWidth: 1, borderDash: [4,4] },
			  pos07:    { type: 'line', yMin: 0.7, yMax: 0.7, borderColor: 'black', borderWidth: 2, borderDash: [4,4] },
			  neg07:    { type: 'line', yMin:-0.7, yMax:-0.7, borderColor: 'black', borderWidth: 2, borderDash: [4,4] }
			}
		  }
		}
	  }
	});
  }
})();
</script>