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

$requires_search = true;
$requires_chartjs = true;

require_once __DIR__ . '/views/header.php';
require_once __DIR__ . '/views/navigation.php';
function getYahooData($symbol, $apiKey) {
	$url = "https://yahoo-finance15.p.rapidapi.com/api/yahoo/qu/quote/$symbol";

	$curl = curl_init();
	curl_setopt_array($curl, [
		CURLOPT_URL => $url,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_HTTPHEADER => [
			"X-RapidAPI-Host: yahoo-finance15.p.rapidapi.com",
			"X-RapidAPI-Key: $apiKey"
		]
	]);
	$response = curl_exec($curl);
	curl_close($curl);
	$data = json_decode($response, true);

	return $data['body'][0] ?? null;
}

function getFredYield($series_id, $apiKey) {
	$url = "https://api.stlouisfed.org/fred/series/observations?series_id=$series_id&api_key=$apiKey&file_type=json&limit=1&sort_order=desc";
	$json = @file_get_contents($url);
	$data = json_decode($json, true);
	return isset($data['observations'][0]['value']) && is_numeric($data['observations'][0]['value']) ? floatval($data['observations'][0]['value']) : null;
}

function wasYieldCurveRecentlyInverted($apiKey, $days = 90) {
	$url10 = "https://api.stlouisfed.org/fred/series/observations?series_id=GS10&api_key=$apiKey&file_type=json&limit=$days&sort_order=desc";
	$url2  = "https://api.stlouisfed.org/fred/series/observations?series_id=GS2&api_key=$apiKey&file_type=json&limit=$days&sort_order=desc";
	
	$data10 = json_decode(@file_get_contents($url10), true)['observations'];
	$data2  = json_decode(@file_get_contents($url2), true)['observations'];
	
	foreach ($data10 as $i => $obs10) {
		$val10 = floatval($obs10['value']);
		$val2 = floatval($data2[$i]['value']);
		if (is_numeric($val10) && is_numeric($val2) && ($val10 - $val2) < 0) {
			return true;
		}
	}
	return false;
}

function getVixFromFred($apiKey) {
	$url = "https://api.stlouisfed.org/fred/series/observations?series_id=VIXCLS&api_key=$apiKey&file_type=json&limit=1&sort_order=desc";
	$json = @file_get_contents($url);
	$data = json_decode($json, true);
	return isset($data['observations'][0]['value']) && is_numeric($data['observations'][0]['value'])
		? floatval($data['observations'][0]['value'])
		: null;
}

function getFearGreedHistory($limit = 7) {
	$url = "https://api.alternative.me/fng/?limit=$limit&format=json";
	$json = @file_get_contents($url);
	$data = json_decode($json, true);
	return $data['data'] ?? [];
}

$riskOnScore = 0;
$signals = [];

// 1. SPY
$spy = getYahooData('SPY', $RapidApiKey);
$spyPrice = $spy['regularMarketPrice'] ?? null;
$sma200 = $spy['twoHundredDayAverage'] ?? null;
$signals[] = [
	'SPY über SMA200',
	$spyPrice && $sma200 && $spyPrice > $sma200,
	$spyPrice && $sma200 ? "SPY: $spyPrice > SMA200: $sma200" : 'n.v.',
	'Langfristiger Trend intakt, Markt eher bullisch'
];
if ($spyPrice && $sma200 && $spyPrice > $sma200) $riskOnScore++;

// 2. High Yield/Investment Grade
$hyg = getYahooData('HYG', $RapidApiKey);
$lqd = getYahooData('LQD', $RapidApiKey);
$hygPrice = $hyg['regularMarketPrice'] ?? null;
$lqdPrice = $lqd['regularMarketPrice'] ?? null;
$ratioHygLqd = ($hygPrice && $lqdPrice) ? round($hygPrice / $lqdPrice, 4) : null;
$hygLqdRiskOn = $ratioHygLqd !== null && $ratioHygLqd > 0.72; // Beispiel-Grenze
$signals[] = [
	'HYG / LQD Ratio',
	$hygLqdRiskOn,
	$ratioHygLqd ? "HYG/LQD: $ratioHygLqd" : 'n.v.',
	'High Yield gegenüber Investment Grade bevorzugt → Risikoappetit'
];
if ($hygLqdRiskOn) $riskOnScore++;

// 3. Gold Kupfer
$kupfer = getYahooData('HG=F', $RapidApiKey);
$gold = getYahooData('GC=F', $RapidApiKey);
$kupferPrice = $kupfer['regularMarketPrice'] ?? null;
$goldPrice = $gold['regularMarketPrice'] ?? null;
$ratioCopperGold = ($kupferPrice && $goldPrice) ? round($kupferPrice / $goldPrice, 4) : null;
$previousRatio = 0.0016;

$ratioRiskOn = $ratioCopperGold !== null && $ratioCopperGold > $previousRatio;
$signals[] = [
	'Kupfer/Gold Ratio (HG1!/GC1!)',
	$ratioRiskOn,
	$ratioCopperGold ? "Kupfer/Gold: $ratioCopperGold" : 'n.v.',
	'Industriemetalle stärker als Gold → Wachstumserwartung'
];
if ($ratioRiskOn) $riskOnScore++;

// 4. AUDUSD/DXY
$aud = getYahooData('AUDUSD=X', $RapidApiKey);
$dxy = getYahooData('DX-Y.NYB', $RapidApiKey);
$audusd = $aud['regularMarketPrice'] ?? null;
$dxyIndex = $dxy['regularMarketPrice'] ?? null;
$aud_ok = $audusd && $audusd > 0.65;
$dxy_ok = $dxyIndex && $dxyIndex < 104;
$signals[] = [
	'AUD/USD ↑ & DXY ↓',
	$aud_ok && $dxy_ok,
	$audusd && $dxyIndex ? "AUD/USD: $audusd | DXY: $dxyIndex" : 'n.v.',
	'Carry-Trades zeigen Risikoaversion oder -freude'
];
if ($aud_ok && $dxy_ok) $riskOnScore++;

// 5. VIX
$vix = getVixFromFred($FredApiKey);
$signals[] = [
	'VIX < 20',
	$vix && $vix < 20,
	$vix ?? 'n.v.',
	'Niedrige Volatilität → Markt gelassen'
];
if ($vix && $vix < 20) $riskOnScore++;


// 6. Zinskurve
$yield10y = getFredYield("GS10", $FredApiKey);
$yield2y = getFredYield("GS2", $FredApiKey);
$spread = ($yield10y !== null && $yield2y !== null) ? round($yield10y - $yield2y, 2) : null;
$recentInversion = wasYieldCurveRecentlyInverted($FredApiKey);

$curveRiskOn = $spread !== null && $spread > 0 && !$recentInversion;

$signals[] = [
	'Zinsstruktur positiv (10Y > 2Y)',
	$curveRiskOn,
	$spread !== null
		? "$yield10y - $yield2y = $spread" . ($recentInversion ? " (zuvor invertiert)" : "")
		: 'n.v.',
	$recentInversion
		? 'Kurve ist zwar positiv, war aber kürzlich invertiert → mögliche Rezession'
		: 'Keine Rezessionserwartung am Anleihemarkt'
];
if ($curveRiskOn) $riskOnScore++;

// 7. Fear & Greed
$fgiHistory = array_reverse(getFearGreedHistory(30));
$fgiCurrent = end($fgiHistory);
$fgiValue = $fgiCurrent['value'] ?? 'n.v.';
$fgiText = $fgiCurrent['value_classification'] ?? 'Unbekannt';

$fgiColor = 'secondary';
if ($fgiText === 'Extreme Fear') $fgiColor = 'danger';
elseif ($fgiText === 'Fear') $fgiColor = 'warning';
elseif ($fgiText === 'Neutral') $fgiColor = 'info';
elseif ($fgiText === 'Greed') $fgiColor = 'success';
elseif ($fgiText === 'Extreme Greed') $fgiColor = 'success';

$fgiLabels = [];
$fgiValues = [];
$fgiColors = [];

foreach ($fgiHistory as $entry) {
	$fgiLabels[] = date('d.m.', $entry['timestamp']);
	$fgiValues[] = (int)$entry['value'];
	switch ($entry['value_classification']) {
		case 'Extreme Fear': $fgiColors[] = 'rgba(220,53,69,0.6)'; break;
		case 'Fear':         $fgiColors[] = 'rgba(255,193,7,0.6)'; break;
		case 'Neutral':      $fgiColors[] = 'rgba(13,110,253,0.6)'; break;
		case 'Greed':        $fgiColors[] = 'rgba(25,135,84,0.6)'; break;
		case 'Extreme Greed':$fgiColors[] = 'rgba(25,135,84,0.8)'; break;
		default:             $fgiColors[] = 'rgba(108,117,125,0.6)';
	}
}

$fgiClassification = strtolower($fgiText);
$fgiRiskOn = in_array($fgiClassification, ['greed', 'extreme greed']);
$signals[] = [
	'Fear & Greed Index',
	$fgiRiskOn,
	"$fgiValue – $fgiText",
	'Stimmungsindikator auf Basis von Volatilität, Momentum & Nachfrage'
];
if ($fgiRiskOn) $riskOnScore++;


// 8. Zyklische/nicht zyklische Werte
$xly = getYahooData('XLY', $RapidApiKey);
$xlp = getYahooData('XLP', $RapidApiKey);
$xlyPrice = $xly['regularMarketPrice'] ?? null;
$xlpPrice = $xlp['regularMarketPrice'] ?? null;
$ratio = ($xlyPrice && $xlpPrice) ? round($xlyPrice / $xlpPrice, 3) : null;
$xlyxlpRiskOn = $ratio !== null && $ratio > 1.5;
$signals[] = [
	'XLY / XLP Ratio',
	$xlyxlpRiskOn,
	$ratio ? "XLY/XLP: $ratio" : 'n.v.',
	'Konsumzykliker vs. Basiskonsum – Risikoneigung im Aktienmarkt'
];
if ($xlyxlpRiskOn) $riskOnScore++;

// 9. High Beta vs. Low Volatility
$sphb = getYahooData('SPHB', $RapidApiKey);
$splv = getYahooData('SPLV', $RapidApiKey);
$sphbPrice = $sphb['regularMarketPrice'] ?? null;
$splvPrice = $splv['regularMarketPrice'] ?? null;
$ratioSPHB = ($sphbPrice && $splvPrice) ? round($sphbPrice / $splvPrice, 3) : null;
	
$sphbsplvRiskOn = $ratioSPHB !== null && $ratioSPHB > 1.0;
$signals[] = [
	'SPHB / SPLV Ratio',
	$sphbsplvRiskOn,
	$ratioSPHB ? "SPHB/SPLV: $ratioSPHB" : 'n.v.',
	'High Beta vs. Low Volatility – Markt risikofreudig bei > 1.0'
];
if ($sphbsplvRiskOn) $riskOnScore++;

// 10. High Yield Spread: BAMLH0A0HYM2
$highYieldSpread = getFredYield('BAMLH0A0HYM2', $FredApiKey);
$highYieldRiskOn = $highYieldSpread !== null && $highYieldSpread < 4.5;
$signals[] = [
	'High Yield Spread (BAML)',
	$highYieldRiskOn,
	$highYieldSpread !== null ? "$highYieldSpread %" : 'n.v.',
	'Niedrige Spreads signalisieren Risikobereitschaft bei < 4.5'
];
if ($highYieldRiskOn) $riskOnScore++;

// 11. TED Spread: TEDRATE
$tedSpread = getFredYield('TEDRATE', $FredApiKey);
$tedRiskOn = $tedSpread !== null && $tedSpread < 0.5;
$signals[] = [
	'TED Spread',
	$tedRiskOn,
	$tedSpread !== null ? "$tedSpread %" : 'n.v.',
	'Geringes Interbankenrisiko deutet auf Vertrauen im Finanzsystem hin bei < 0.5'
];
if ($tedRiskOn) $riskOnScore++;

// 12. BTC 200 SMA
$btc = getYahooData('BTC-USD', $RapidApiKey);
$btcPrice = $btc['regularMarketPrice'] ?? null;
$btcSma200 = $btc['twoHundredDayAverage'] ?? null;

$btcRiskOn = $btcPrice && $btcSma200 && $btcPrice > $btcSma200;
$signals[] = [
	'Bitcoin über SMA200',
	$btcRiskOn,
	$btcPrice && $btcSma200 ? "BTC: $btcPrice > SMA200: $btcSma200" : 'n.v.',
	'Langfristige Stärke im Krypto-Markt → Risikoaffinität'
];
if ($btcRiskOn) $riskOnScore++;

// 13. GVZ (Gold Volatility Index)
$gvz = getYahooData('%5EGVZ', $RapidApiKey);
$gvzValue = $gvz['regularMarketPrice'] ?? null;

$gvzClassification = 'n.v.';
$gvzRiskOn = false;

if ($gvzValue !== null) {
	if ($gvzValue > 25) {
		$gvzClassification = 'Panik / Flucht in Sicherheit';
		$gvzRiskOn = false;
	} elseif ($gvzValue > 18) {
		$gvzClassification = 'Absicherung nimmt zu';
		$gvzRiskOn = false;
	} elseif ($gvzValue >= 13) {
		$gvzClassification = 'Normal – moderates Inflationsszenario';
		$gvzRiskOn = true;
	} else {
		$gvzClassification = 'Markt ignoriert Gold – Ruhe';
		$gvzRiskOn = true;
	}
}

$signals[] = [
	'Gold Volatility Index (GVZ)',
	$gvzRiskOn,
	$gvzValue !== null ? number_format($gvzValue, 2) . ' – ' . $gvzClassification : 'n.v.',
	'Goldvolatilität als Spiegel für Angst, Sicherheit & Absicherung'
];

if ($gvzRiskOn) $riskOnScore++;

// SCORE BERECHNEN
$maxScore = count($signals);
$status = $riskOnScore >= 5 ? '🟢 Klar Risk-On' : ($riskOnScore >= 3 ? '🟡 Neutral' : '🔴 Risk-Off');
$scorePercent = intval(($riskOnScore / $maxScore) * 100);
$badgeColor = $riskOnScore >= 5 ? 'success' : ($riskOnScore >= 3 ? 'warning' : 'danger');
?>
<main class="flex-grow-1">
	<div class="container my-5">
		<h2 class="card-title mb-3">Risk-On / Risk-Off Indikator</h2>
		<p class="mb-2">
			<strong>Status:</strong>
			<?= $status ?> (<?= $riskOnScore ?> von <?= $maxScore ?> erfüllt)
		</p>
		
		<div class="progress mb-4" style="height: 20px;">
			<div class="progress-bar bg-<?= $badgeColor ?>" role="progressbar"
				style="width: <?= $scorePercent ?>%;" aria-valuenow="<?= $scorePercent ?>"
				aria-valuemin="0" aria-valuemax="100">
				<?= $scorePercent ?>%
			</div>
		</div>
		
		<div class="table-responsive">
			<table class="table table-striped align-middle">
				<thead class="table-dark">
					<tr>
						<th>#</th>
						<th>Signal</th>
						<th>Status</th>
						<th>Wert(e)</th>
						<th>Bewertung</th>
					</tr>
				</thead>
				<tbody>
				<?php $index = 1; ?>
				<?php foreach ($signals as [$label, $ok, $wert, $bewertung]): ?>
					<tr>
						<td><?= $index++ ?>.</td>
						<td><?= $label ?></td>
						<td>
							<span class="badge <?= $ok ? 'bg-success' : 'bg-danger' ?> text-white"><?= $ok ? 'Risk-On' : 'Risk-Off' ?></span>
						</td>
						<td><?= $wert ?></td>
						<td><?= $bewertung ?></td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>	
			<div class="card mt-5">
				<div class="card-body">
					<h5 class="card-title">Fear & Greed Index</h5>
					<span class="badge bg-<?= $fgiColor ?> fs-7">
						<?= $fgiValue ?> – <?= $fgiText ?>
					</span>
					<canvas id="fgiChart" height="100"></canvas>
				</div>
			</div>
			
			<script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
			<div class="card mt-3">
			<div class="card-body">
				<h5 class="card-title">MMTH (%Stocks above 200 Avg)</h5>
				<small class="text-muted">Markt risikofreudig bei > 50%</small>
				<div class="tradingview-widget-container mt-3">
				<div id="tradingview_mmth"></div>
				<script type="text/javascript">
					new TradingView.widget({
					"width": "100%",
					"height": 400,
					"symbol": "MMTH",
					"interval": "D",
					"timezone": "Etc/UTC",
					"theme": "light",
					"style": "1",
					"locale": "de",
					"toolbar_bg": "#f1f3f6",
					"enable_publishing": false,
					"allow_symbol_change": true,
					"container_id": "tradingview_mmth"
					});
				</script>
				</div>
			</div>
			</div>
			<div class="card mt-3">
			<div class="card-body">
				<h5 class="card-title">HYG/LQD Ratio (High Yield Bonds / Investment Grade Bonds)</h5>
				<small class="text-muted">Risk on bei steigendem Kursverlauf</small>
				<div class="tradingview-widget-container mt-3">
				<div id="tradingview_hyglqd"></div>
				<script type="text/javascript">
					new TradingView.widget({
					"width": "100%",
					"height": 400,
					"symbol": "AMEX:HYG/AMEX:LQD",
					"interval": "D",
					"timezone": "Etc/UTC",
					"theme": "light",
					"style": "1",
					"locale": "de",
					"toolbar_bg": "#f1f3f6",
					"enable_publishing": false,
					"allow_symbol_change": true,
					"container_id": "tradingview_hyglqd"
					});
				</script>
				</div>
			</div>
			</div>
			<div class="card mt-3">
			<div class="card-body">
				<h5 class="card-title">XLY/XLP Ratio (Consumer Discretionary / Consumer Staples)</h5>
				<small class="text-muted">Risk on bei steigendem Kursverlauf</small>
				<div class="tradingview-widget-container mt-3">
				<div id="tradingview_xlyxlp"></div>
				<script type="text/javascript">
					new TradingView.widget({
					"width": "100%",
					"height": 400,
					"symbol": "AMEX:XLY/AMEX:XLP",
					"interval": "D",
					"timezone": "Etc/UTC",
					"theme": "light",
					"style": "1",
					"locale": "de",
					"toolbar_bg": "#f1f3f6",
					"enable_publishing": false,
					"allow_symbol_change": true,
					"container_id": "tradingview_xlyxlp"
					});
				</script>
				</div>
			</div>
			</div>
			<div class="card mt-3">
			<div class="card-body">
				<h5 class="card-title">SPHB/SPLV (High Beta vs. Low Volatility)</h5>
				<small class="text-muted">Markt risikofreudig bei > 1.0</small>
				<div class="tradingview-widget-container mt-3">
				<div id="tradingview_sphbsplv"></div>
				<script type="text/javascript">
					new TradingView.widget({
					"width": "100%",
					"height": 400,
					"symbol": "AMEX:SPHB/AMEX:SPLV",
					"interval": "D",
					"timezone": "Etc/UTC",
					"theme": "light",
					"style": "1",
					"locale": "de",
					"toolbar_bg": "#f1f3f6",
					"enable_publishing": false,
					"allow_symbol_change": true,
					"container_id": "tradingview_sphbsplv"
					});
				</script>
				</div>
			</div>
			</div>
		</div>
		
	</div>
</main>

<script>
  const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
  const tooltipList = tooltipTriggerList.map(t => new bootstrap.Tooltip(t))
</script>
<script>
	const ctx = document.getElementById('fgiChart').getContext('2d');
	new Chart(ctx, {
		type: 'line',
		data: {
			labels: <?= json_encode($fgiLabels) ?>,
			datasets: [{
				label: 'Fear & Greed Index',
				data: <?= json_encode($fgiValues) ?>,
				backgroundColor: <?= json_encode($fgiColors) ?>,
				borderColor: 'rgba(0,0,0,0.3)',
				tension: 0.3,
				fill: true,
				pointRadius: 5,
				pointHoverRadius: 7
			}]
		},
		options: {
			responsive: true,
			scales: {
				y: {
					beginAtZero: true,
					suggestedMax: 100
				}
			}
		}
	});
</script>
<?php require_once __DIR__ . '/views/footer.php'; ?>