<?php
require_once __DIR__ . '/engine/engine.php';
require_once __DIR__ . '/engine/api-handling/fmp_client.php';
require_once __DIR__ . '/engine/bewertungsmethoden/bewertung_korrelationen.php';

$requires_search = true;
$requires_chartjs = true;
$requires_dataTables = true;

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

$symbol = $_GET['symbol'] ?? '';
$corrData = bewertung_korrelationen_run($symbol);

$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 = fn($v,$d=2)=> ($v===null ? '—' : number_format($v, $d, ',', '.'));

$sectorLabel = $corrData['meta']['sector'] ?? null;
$sectorEtf   = $corrData['meta']['sector_etf'] ?? null;
$leadlag     = $corrData['leadlag'] ?? null;
?>
<main class="flex-grow-1">
	<div class="container pb-5">
		<div class="row">
			<div class="col-12">
				<div class="sticky-top mt-5 bg-white z-3 pb-3">
					<div class="d-flex justify-content-between">
						<h1 class="mb-4">Korrelationen</h1>
						<div>
						<?php
							if ($symbol) {
								$category = 'Korrelationen';
								include 'execute/watchlist/watchlist_button.php';
							}
						?>
						</div>
					</div>
					<form method="get">
						<label for="symbol" class="form-label">Symbol eingeben:</label>
						<div class="input-group">
							<input type="text" class="form-control symbol-autocomplete" name="symbol" id="symbol" placeholder="AAPL" value="<?= htmlspecialchars($symbol) ?>" required>
							<button type="submit" class="btn btn-dark">Prüfen</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		
		<?php if (!empty($corrData['error'])): ?>
			<div class="alert alert-danger"><?= htmlspecialchars($corrData['error']) ?></div>
		<?php else: ?>
			
			<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): ?>
									<small class="text-muted me-2">Sektor: <?= htmlspecialchars($sectorLabel) ?></small>
								<?php endif; ?>
								<?php if ($sectorEtf): ?>
									<small class="text-muted">Sektor-ETF: <?= htmlspecialchars($sectorEtf) ?></small>
								<?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="corrBar" height="80"></canvas>
							<div class="table-responsive mt-4">
								<table class="table align-middle" id="corrTable">
									<thead class="table-dark">
										<tr>
											<th>Benchmark</th>
											<th>Erklärung</th>
											<th><?= (int)$corrData['windows'][0] ?>d</th>
											<th><?= (int)$corrData['windows'][1] ?>d</th>
											<th><?= (int)$corrData['windows'][2] ?>d</th>
										</tr>
									</thead>
									<tbody></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="corrRolling" height="90" class="mt-2"></canvas>
						</div>
					</div>
				</div>
			</div>
			
		<?php endif; ?>
	</div>
</main>

<?php if (empty($corrData['error'])): ?>
<script>
  (function(){
	  
	const 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 (Langläufer-UST)",
	  HYG:  "iShares iBoxx $ High Yield Corporate Bond",
	  UUP:  "Invesco DB US Dollar Index Bullish (USD-Index-Proxy)",
	  GLD:  "SPDR Gold Shares",
	  USO:  "United States Oil Fund",
	  VIXY: "ProShares VIX Short-Term Futures (Vola-Proxy)",
	  // Sektor-ETFs (falls via Profil dynamisch ergänzt)
	  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"
	};  
	  
	const data = <?= json_encode($corrData, 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); }

	// Tabelle füllen (nach 90d sortieren)
	const tbody = document.querySelector('#corrTable tbody');
	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;
	});

	tbody.innerHTML = '';
	rows.forEach(r => {
	  const info = ETF_INFO[r.symbol] || `Benchmark: ${r.symbol}`;
	  const tr = document.createElement('tr');
	  tr.innerHTML = `
		<td class="fw-bold">${r.symbol}</td>
		<td>${info}</td>
		<td>${fmt(r.corr?.[winA])}</td>
		<td>${fmt(r.corr?.[winB])}</td>
		<td>${fmt(r.corr?.[winC])}</td>
	  `;
	  tbody.appendChild(tr);
	});

	// Optional: Wenn DataTables geladen ist, initialisieren
	if (window.jQuery && jQuery.fn && jQuery.fn.DataTable && !jQuery.fn.dataTable.isDataTable('#corrTable')) {
	  jQuery('#corrTable').DataTable({
		paging: false, searching: false, info: false, order: []
	  });
	}

	// Bar-Chart (90d)
	if (window.Chart) {
	  const labels = rows.map(r=> r.symbol);
	  const vals90  = rows.map(r=> r.corr?.[winB]);
	  if (window._corrBar) window._corrBar.destroy();
	  const ctxBar = document.getElementById('corrBar').getContext('2d');
	  window._corrBar = new Chart(ctxBar, {
		type: 'bar',
		data: { 
			labels,
			datasets: [{ 
				label: `${winB}-Tage Korrelation zu ${data.symbol}`, data: vals90,
				borderColor: 'black',
				backgroundColor: 'black'
			}] },
		options: {
		  responsive: true,
		  scales: { y: { min: -1, max: 1 } },
		  plugins: {
			tooltip: {
			  callbacks: {
				title: (items) => {
				  const sym = items?.[0]?.label || '';
				  return `${sym} — ${ETF_INFO[sym] || 'Benchmark'}`;
				},
				label: (ctx) => `${ctx.dataset.label}: ${fmt(ctx.raw)}`
			  }
			},
			legend: { labels: { color: 'black' } }
		  }
		}
	  });
	}

	// Rolling (90d) vs SPY
	if (window.Chart) {
	  const roll = data.rolling || [];
	  const labelsR = roll.map(d=> d.date);
	  const valsR   = roll.map(d=> d.corr);
	
	  if (window._corrRoll) window._corrRoll.destroy();
	  const ctxRoll = document.getElementById('corrRolling').getContext('2d');
	  window._corrRoll = 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: 2
		  }]
		},
		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: 'black',
				  borderWidth: 1,
				  borderDash: [6, 6],
				  label: {
					display: true,
					content: '0',
					position: 'end',
					color: 'red'
				  }
				},
				highPosLine: {
				  type: 'line',
				  yMin: 0.7,
				  yMax: 0.7,
				  borderColor: 'green',
				  borderWidth: 2,
				  borderDash: [6, 6],
				  label: {
					display: true,
					content: '+0.7',
					position: 'end',
					color: 'red'
				  }
				},
				midPosLine: {
				  type: 'line',
				  yMin: 0.4,
				  yMax: 0.4,
				  borderColor: 'green',
				  borderWidth: 1,
				  borderDash: [6, 6],
				  label: {
					display: true,
					content: '+0.4',
					position: 'end',
					color: 'black'
				  }
				},
				highNegLine: {
				  type: 'line',
				  yMin: -0.7,
				  yMax: -0.7,
				  borderColor: 'red',
				  borderWidth: 2,
				  borderDash: [6, 6],
				  label: {
					display: true,
					content: '-0.7',
					position: 'start',
					color: 'black'
				  }
				},
				midNegLine: {
				  type: 'line',
				  yMin: -0.4,
				  yMax: -0.4,
				  borderColor: 'red',
				  borderWidth: 1,
				  borderDash: [6, 6],
				  label: {
					display: true,
					content: '-0.4',
					position: 'start',
					color: 'black'
				  }
				}
			  }
			}
		  }
		}
	  });
	}
  })();
  </script>
<?php endif; ?>

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