<?php
require_once __DIR__ . '/engine/engine.php';
require_once __DIR__ . '/engine/api-handling/api_helpers.php';
$requires_search = true;
$requires_chartjs = true;
require_once __DIR__ . '/views/header.php';
require_once __DIR__ . '/views/navigation.php';

$stmt = $pdo->query("SELECT DATE_FORMAT(created_at, '%d.%m.') AS label, score, `signal` FROM scores ORDER BY created_at ASC");
$scoreData = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $pdo->query("SELECT score, `signal`, created_at, details FROM scores ORDER BY created_at DESC LIMIT 1");
$latest = $stmt->fetch(PDO::FETCH_ASSOC);

// Daten bei Klick auf Button laden?
$updateTriggered = isset($_POST['update_score']);

// Funktion zum Speichern
function saveScore($pdo, $score, $signalText, $detailsArray) {
	$detailsText = implode("\n", $detailsArray);
	$stmt = $pdo->prepare("INSERT INTO scores (score, `signal`, created_at, details) VALUES (?, ?, NOW(), ?)");
	$stmt->execute([$score, $signalText, $detailsText]);
}

// Nur laden, wenn Button gedrückt
if ($updateTriggered) {

	$fredSeries = [
		'inflation' => 'CPIAUCSL',
		'unemployment' => 'UNRATE',
		'gdp' => 'GDPC1',
		'fed_rate' => 'FEDFUNDS',
		'm2' => 'M2SL',
		'balance_sheet' => 'WALCL',
		'high_yield_spread' => 'BAMLH0A0HYM2',
		'vix' => 'VIXCLS'
	];

	function fetchFredData($seriesId, $FredApiKey) {
		$url = "https://api.stlouisfed.org/fred/series/observations?series_id=$seriesId&api_key=$FredApiKey&file_type=json";
		$response = file_get_contents($url);
		$data = json_decode($response, true);
		return $data['observations'] ?? [];
	}

	function fetchYahooClose($symbol, $days, $rapidApiKey) {
		$url = "https://yahoo-finance15.p.rapidapi.com/api/v2/markets/stock/history?symbol=$symbol&interval=1d&limit=$days";

		$curl = curl_init();
		curl_setopt_array($curl, [
			CURLOPT_URL => $url,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_HTTPHEADER => [
				"x-rapidapi-key: $rapidApiKey",
				"x-rapidapi-host: yahoo-finance15.p.rapidapi.com"
			]
		]);

		$response = curl_exec($curl);
		curl_close($curl);

		$data = json_decode($response, true);

		if (!isset($data['body']) || !is_array($data['body'])) {
			return [];
		}

		return array_reverse($data['body']);
	}

	function calculateScore($fredData, &$details, $rapidApiKey) {
		$score = 0;
		$details = [];

		$inflationCount = count($fredData['inflation']);
		if ($inflationCount >= 13) {
			$inflationRecent = floatval(end($fredData['inflation'])['value']);
			$inflationOld = floatval($fredData['inflation'][$inflationCount - 13]['value']);
			$inflationPoints = ($inflationRecent < $inflationOld) ? 10 : 0;
			$details[] = "Inflation: $inflationRecent vs. $inflationOld → +$inflationPoints Punkte";
			$score += $inflationPoints;
		} else {
			$details[] = "Inflation: Nicht genug Daten vorhanden.";
		}

		$unemployment = floatval(end($fredData['unemployment'])['value']);
		$unemploymentPoints = ($unemployment < 5) ? 10 : 0;
		$details[] = "Arbeitslosenquote: $unemployment% → +$unemploymentPoints Punkte";
		$score += $unemploymentPoints;

		$gdpRecent = floatval(end($fredData['gdp'])['value']);
		$gdpPoints = ($gdpRecent > 0) ? 10 : 0;
		$details[] = "BIP-Wachstum: $gdpRecent → +$gdpPoints Punkte";
		$score += $gdpPoints;
		
		$vixData = $fredData['vix'];
		$vixValue = null;
		
		if (!empty($vixData)) {
			for ($i = count($vixData) - 1; $i >= 0; $i--) {
				$val = $vixData[$i]['value'];
				if ($val !== ".") {
					$vixValue = (float)$val;
					break;
				}
			}
		
			if ($vixValue !== null) {
				$vixPoints = ($vixValue < 20) ? 10 : 0;
				$details[] = "VIX: $vixValue → +$vixPoints Punkte";
				$score += $vixPoints;
			} else {
				$details[] = "VIX: Kein gültiger Wert gefunden.";
			}
		} else {
			$details[] = "VIX: Keine Daten gefunden.";
		}

		$spxData = fetchYahooClose('SPY', 300, $rapidApiKey);
		$closePrices = array_column($spxData, 'close');
		if (count($closePrices) >= 200) {
			$sma200 = array_sum(array_slice($closePrices, -200)) / 200;
			$smaPoints = (end($closePrices) > $sma200) ? 10 : 0;
			$details[] = "S&P 500 Schlusskurs vs. 200-Tage-SMA: " . round(end($closePrices), 2) . " > " . round($sma200, 2) . " → +$smaPoints Punkte";
			$score += $smaPoints;
		} else {
			$details[] = "S&P 500: Nicht genug Kursdaten.";
		}

		if (count($closePrices) >= 10) {
			$momentum = end($closePrices) - $closePrices[count($closePrices) - 10];
			$momentumPoints = ($momentum > 0) ? 10 : 0;
			$details[] = "Momentum (10 Tage): $momentum → +$momentumPoints Punkte";
			$score += $momentumPoints;
		} else {
			$details[] = "Momentum: Nicht genug Kursdaten vorhanden.";
		}

		$m2Recent = floatval(end($fredData['m2'])['value']);
		$m2Old = floatval($fredData['m2'][count($fredData['m2']) - 13]['value']);
		$m2Points = ($m2Recent > $m2Old) ? 10 : 0;
		$details[] = "Geldmenge M2: $m2Recent vs. $m2Old → +$m2Points Punkte";
		$score += $m2Points;

		$spread = floatval(end($fredData['high_yield_spread'])['value']);
		$spreadPoints = ($spread < 4) ? 10 : 0;
		$details[] = "High Yield Spread: $spread → +$spreadPoints Punkte";
		$score += $spreadPoints;

		$balanceRecent = floatval(end($fredData['balance_sheet'])['value']);
		$balanceOld = floatval($fredData['balance_sheet'][count($fredData['balance_sheet']) - 13]['value']);
		$balancePoints = ($balanceRecent > $balanceOld) ? 10 : 0;
		$details[] = "Zentralbankbilanz: $balanceRecent vs. $balanceOld → +$balancePoints Punkte";
		$score += $balancePoints;

		return $score;
	}

	$fredData = [];
	foreach ($fredSeries as $key => $seriesId) {
		$fredData[$key] = fetchFredData($seriesId, $FredApiKey);
	}

	$details = [];
	$score = calculateScore($fredData, $details, $RapidApiKey);
	$signal = $score > 60 ? 'success' : ($score > 30 ? 'warning' : 'danger');
	$signalText = $score > 60 ? 'Investieren erlaubt' : ($score > 30 ? 'Vorsicht geboten' : 'Risiko meiden');

	$lastStmt = $pdo->query("SELECT id, score, `signal` FROM scores ORDER BY created_at DESC LIMIT 1");
	$lastEntry = $lastStmt->fetch(PDO::FETCH_ASSOC);
	
	if ($lastEntry && (int)$lastEntry['score'] === $score) {
		$deleteStmt = $pdo->prepare("DELETE FROM scores WHERE id = ?");
		$deleteStmt->execute([$lastEntry['id']]);
	}
	
	saveScore($pdo, $score, $signalText, $details);
}

?>
<main class="flex-grow-1">
	<section>
		<div class="container py-5">
			<h2 class="mb-4">Macro Sentiment Score</h2>
			<?php if ($latest): ?>
			  <?php
				$badge = match ($latest['signal']) {
					'Investieren erlaubt' => 'success',
					'Vorsicht geboten' => 'warning',
					'Risiko meiden' => 'danger',
					default => 'secondary',
				};
			  ?>
			  <div class="alert alert-<?= $badge ?>" role="alert">
				<small>Letzter Stand: <?= date('d.m.Y H:i', strtotime($latest['created_at'])) ?></small>
				<h3>Score: <strong><?= $latest['score'] ?>/90</strong></h3>
				<span class="badge bg-<?= $badge ?>"><?= $latest['signal'] ?></span> 
				<hr/>
				<?php if (!empty($latest['details'])): ?>
				  <h6 class="mt-3">Details zur Bewertung:</h6>
				  <ul class="small">
					<?php foreach (explode("\n", $latest['details']) as $line): ?>
					  <li><?= htmlspecialchars(trim($line)) ?></li>
					<?php endforeach; ?>
				  </ul>
				<?php endif; ?>
			  </div>
			<?php endif; ?>
			<form method="post">
				<button class="btn btn-dark" type="submit" name="update_score">Score neu berechnen & speichern</button>
			</form>
			<div class="my-5">
				<canvas id="scoreChart" height="80"></canvas>
			</div>
		
			<?php if ($updateTriggered): ?>
				<div class="card border-<?= $signal ?>">
					<div class="card-body">
						<h2 class="card-title">Gesamtscore: <?= $score ?>/90</h2>
						<p class="card-text">Marktklima: <span class="text-<?= $signal ?> fw-bold"><?= $signalText ?></span></p>
						<hr>
						<h5>Details zur Bewertung:</h5>
						<ul>
						<?php foreach ($details as $detail): ?>
							<li><?= htmlspecialchars($detail) ?></li>
						<?php endforeach; ?>
						</ul>
					</div>
				</div>
			<?php endif; ?>
			
			<div class="mt-4 p-3 bg-white border rounded shadow-sm">
				<h5>Bewertung</h5>
				<ul>
					<li><strong><span class="badge text-bg-success text-white">Score 61–90</span></strong> Marktklima positiv – neue Positionen aufbauen, ETFs oder starke Wachstumswerte kaufen.</li>
					<li><strong><span class="badge text-bg-warning text-white">Score 31–60</span></strong> Durchwachsen – selektive Investments möglich, Fokus auf Qualität & Risikomanagement.</li>
					<li><strong><span class="badge text-bg-danger text-white">Score 0–30</span></strong> Warnzone – Absicherung aktivieren, Positionen reduzieren, Cashquote erhöhen.</li>
				</ul>
				<p class="mb-0 text-muted"><small>Hinweis: Der Indikator ist ein übergeordneter Stimmungsindikator – nutze ihn für strategische Orientierung, nicht für kurzfristige Trades.</small></p>
			</div>
			
			<?php if (count($scoreData) > 0): ?>
			  <div class="mt-5">
				<h5>Score-Historie</h5>
				<div class="table-responsive">
				  <table class="table table-bordered align-middle text-center">
					<thead class="table-light">
					  <tr>
						<th>Datum</th>
						<th>Score</th>
						<th>Signal</th>
					  </tr>
					</thead>
					<tbody>
					  <?php foreach (array_reverse($scoreData) as $row): ?>
						<tr>
						  <td><?= htmlspecialchars($row['label']) ?></td>
						  <td><?= (int)$row['score'] ?></td>
						  <td>
							<?php
							  $color = match ($row['signal']) {
								  'Investieren erlaubt' => 'success',
								  'Vorsicht geboten' => 'warning',
								  'Risiko meiden' => 'danger',
								  default => 'secondary',
							  };
							?>
							<span class="badge bg-<?= $color ?>"><?= htmlspecialchars($row['signal']) ?></span>
						  </td>
						</tr>
					  <?php endforeach; ?>
					</tbody>
				  </table>
				</div>
			  </div>
			<?php endif; ?>
		</div>
	</section>
	<?php
		$stmt = $pdo->query("SELECT DATE_FORMAT(created_at, '%d.%m.%Y %H:%i') AS label, score, `signal` FROM scores ORDER BY created_at ASC");
		$scoreData = $stmt->fetchAll(PDO::FETCH_ASSOC);
		
		$labels = [];
		$scores = [];
		$colors = [];
		
		foreach ($scoreData as $row) {
			$labels[] = $row['label'];
			$scores[] = (int)$row['score'];
			$colors[] = match ($row['signal']) {
				'Investieren erlaubt' => 'rgba(40,167,69,0.7)',
				'Vorsicht geboten' => 'rgba(255,193,7,0.7)',
				'Risiko meiden' => 'rgba(220,53,69,0.7)',
				default => 'rgba(108,117,125,0.7)',
			};
		}
	?>
	<script>
	const ctx = document.getElementById('scoreChart').getContext('2d');
	const scoreChart = new Chart(ctx, {
		type: 'line',
		data: {
			labels: <?= json_encode($labels) ?>,
			datasets: [{
				label: 'Score',
				data: <?= json_encode($scores) ?>,
				backgroundColor: <?= json_encode($colors) ?>,
				borderColor: 'rgba(33,37,41,1)',
				fill: false,
				tension: 0.3,
				pointRadius: 4,
				pointHoverRadius: 6
			}]
		},
		options: {
			responsive: true,
			scales: {
				x: {
					ticks: {
						maxRotation: 45,
						minRotation: 30,
						autoSkip: true,
						maxTicksLimit: 10
					}
				},
				y: {
					min: 0,
					max: 90,
					ticks: { stepSize: 10 }
				}
			},
			plugins: {
				legend: { display: false },
				tooltip: {
					callbacks: {
						label: function(context) {
							return 'Score: ' + context.parsed.y + ' am ' + context.label;
						}
					}
				}
			}
		}
	});
	</script>
</main>
<?php require_once __DIR__ . '/views/footer.php'; ?>