<?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';

$logFile = __DIR__ . '/execute/sektoren/sektor_performance_log.json';

$historyFile = __DIR__ . '/execute/sektoren/sektor_performance_history.json';

if (!file_exists($historyFile)) {
	file_put_contents($historyFile, '{}');
}

$historyRaw = file_get_contents($historyFile);
$history = json_decode($historyRaw, true);

if (!is_array($history)) {
	$history = [];
}

// Vorhandene Tagesdaten laden
$yesterdayData = file_exists($logFile) ? json_decode(file_get_contents($logFile), true) ?? [] : [];

// S&P 500 laden
$constituentsUrl = "https://financialmodelingprep.com/api/v3/sp500_constituent?apikey=$FmpApiKey";
$sp500 = json_decode(file_get_contents($constituentsUrl), true);

$symbolToSector = [];
foreach ($sp500 as $stock) {
	if (!empty($stock['symbol']) && !empty($stock['sector'])) {
		$symbolToSector[$stock['symbol']] = $stock['sector'];
	}
}

$symbols = array_keys($symbolToSector);
$sectorPerf = [];
$batchSize = 100;

// Quotes laden
for ($i = 0; $i < count($symbols); $i += $batchSize) {
	$batch = array_slice($symbols, $i, $batchSize);
	$quoteUrl = "https://financialmodelingprep.com/api/v3/quote/" . implode(',', $batch) . "?apikey=$FmpApiKey";
	$quoteData = json_decode(file_get_contents($quoteUrl), true);
	if (!is_array($quoteData)) continue;

	foreach ($quoteData as $q) {
		$symbol = $q['symbol'] ?? null;
		$change = $q['changesPercentage'] ?? null;

		if ($symbol && isset($symbolToSector[$symbol]) && is_numeric($change)) {
			$sector = $symbolToSector[$symbol];
			if (!isset($sectorPerf[$sector])) {
				$sectorPerf[$sector] = ['sum' => 0, 'count' => 0];
			}
			$sectorPerf[$sector]['sum'] += $change;
			$sectorPerf[$sector]['count'] += 1;
		}
	}
	usleep(250000);
}

// Funktion zur Berechnung gleitender Durchschnittswerte
function calcAvg(array $history, string $sector, int $days): ?float {
	$values = [];
	foreach (array_reverse($history) as $daily) {
		if (isset($daily[$sector])) $values[] = $daily[$sector];
		if (count($values) >= $days) break;
	}
	return count($values) > 0 ? round(array_sum($values) / count($values), 2) : null;
}

// Heute berechnen und speichern
$todayKey = date('Y-m-d');
$todayPerf = [];
$sectors = [];

foreach ($sectorPerf as $sector => $data) {
	if ($data['count'] > 0) {
		$avg = $data['sum'] / $data['count'];
		$todayPerf[$sector] = round($avg, 2);
	}
}

$history[$todayKey] = $todayPerf;
file_put_contents($historyFile, json_encode(array_slice($history, -300, true), JSON_PRETTY_PRINT));
$history = array_slice($history, -300, true);
file_put_contents($logFile, json_encode($todayPerf, JSON_PRETTY_PRINT));
file_put_contents($historyFile, json_encode($history, JSON_PRETTY_PRINT));

// Frühindikator und vollständige Sektorwerte
$earlySignals = [];

foreach ($todayPerf as $sector => $todayVal) {
	$yesterday = $yesterdayData[$sector] ?? null;

	// Frühindikator: kurzfristig stark positiv nach gestriger Schwäche
	if ($yesterday !== null && $yesterday < -0.2 && $todayVal > 0.3) {
		$earlySignals[] = [
			'type' => 'Tageswende',
			'sector' => $sector,
			'details' => "Gestern: {$yesterday} %, heute: {$todayVal} %"
		];
	}

	// Frühindikator: mittelfristiger Durchbruch nach schwacher Woche/Monat
	$avg1w = calcAvg($history, $sector, 5);
	$avg1m = calcAvg($history, $sector, 20);

	if (($avg1w < 0 || $avg1m < 0) && $todayVal > 0.3) {
		$earlySignals[] = [
			'type' => 'Trendwende',
			'sector' => $sector,
			'details' => "1W: {$avg1w} %, 1M: {$avg1m} %, heute: {$todayVal} %"
		];
	}
}

foreach ($todayPerf as $sector => $todayVal) {
	$avg1w = calcAvg($history, $sector, 5);
	$avg1m = calcAvg($history, $sector, 20);
	$avg3m = calcAvg($history, $sector, 60);
	$avg6m = calcAvg($history, $sector, 120);
	$avg12m = calcAvg($history, $sector, 240);

	$sectors[] = [
		'sector' => $sector,
		'avg_today' => round($todayVal, 2),
		'avg_1w' => $avg1w,
		'avg_1m' => $avg1m,
		'avg_3m' => $avg3m,
		'avg_6m' => $avg6m,
		'avg_12m' => $avg12m,
		'stocks' => $sectorPerf[$sector]['count'] ?? 0
	];
}

usort($sectors, fn($a, $b) => $b['avg_today'] <=> $a['avg_today']);

$maxToday = null;
$minToday = null;
foreach ($sectors as $entry) {
	$val = $entry['avg_today'];
	if ($maxToday === null || $val > $maxToday) $maxToday = $val;
	if ($minToday === null || $val < $minToday) $minToday = $val;
}

?>

<main class="flex-grow-1">
	<section>
		<div class="container my-5">
			<div class="row">
				<div class="col-12">
					<h1>Sektor-Rotation</h1>
					<p class="mb-0">Basierend auf Tages- und Mehrperiodenmomentum </p>
					<small class="text-muted">Stand: <?= date('d.m.Y H:i:s') ?></small>
					
					<div class="table-responsive mt-3 mb-3">
						<table class="table table-bordered align-middle">
							<thead class="table-light">
								<tr>
									<th>#</th>
									<th>Sektor</th>
									<th>Heute</th>
									<th>1W</th>
									<th>1M</th>
									<th>3M</th>
									<th>6M</th>
									<th>12M</th>
									<th>Anzahl Aktien</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ($sectors as $i => $entry): ?>
									<?php
										$isBullish = $entry['avg_today'] === $maxToday;
										$isBearish = $entry['avg_today'] === $minToday;
										$rowClass = $isBullish ? 'table-success' : ($isBearish ? 'table-danger' : '');
									?>
									<tr<?= $rowClass ? ' class="' . $rowClass . '"' : '' ?>>
										<td><?= $i + 1 ?></td>
										<td class="fw-bold"><?= htmlspecialchars($entry['sector']) ?></td>
										<?php foreach (['avg_today', 'avg_1w', 'avg_1m', 'avg_3m', 'avg_6m', 'avg_12m'] as $col): ?>
											<?php
												$val = $entry[$col];
												$arrow = $val >= 0 ? '↑' : '↓';
												$formatted = ($val >= 0 ? '+' : '') . $val;
											?>
											<td class="<?= $val >= 0 ? 'text-success' : 'text-danger' ?>">
												<?= $arrow . ' ' . $formatted ?> %
											</td>
										<?php endforeach; ?>
										<td><?= $entry['stocks'] ?></td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>
				</div>
			</div>
			<div class="row">
				<div class="col-md-6">		
					<div class="card">
						<div class="card-body text-center">
							<script>
								const sectorLabels = <?= json_encode(array_column($sectors, 'sector')) ?>;
								const dataToday = <?= json_encode(array_column($sectors, 'avg_today')) ?>;
								const data1w = <?= json_encode(array_column($sectors, 'avg_1w')) ?>;
								const data1m = <?= json_encode(array_column($sectors, 'avg_1m')) ?>;
								const data3m = <?= json_encode(array_column($sectors, 'avg_3m')) ?>;
								const data6m = <?= json_encode(array_column($sectors, 'avg_6m')) ?>;
								const data12m = <?= json_encode(array_column($sectors, 'avg_12m')) ?>;
								const dataYesterday = <?= json_encode(array_map(fn($s) => $yesterdayData[$s['sector']] ?? null, $sectors)) ?>;
							</script>
							<div class="mb-2">
								<div class="btn-group btn-group-sm" role="group" id="toggleButtons">
									<button type="button" class="btn btn-outline-secondary" data-dataset="Heute">Heute</button>
									<button type="button" class="btn btn-outline-secondary active" data-dataset="1 Woche">1 Woche</button>
									<button type="button" class="btn btn-outline-secondary active" data-dataset="1 Monat">1 Monat</button>
									<button type="button" class="btn btn-outline-secondary" data-dataset="3 Monate">3 Monate</button>
									<button type="button" class="btn btn-outline-secondary" data-dataset="6 Monate">6 Monate</button>
									<button type="button" class="btn btn-outline-secondary" data-dataset="12 Monate">12 Monate</button>
								</div>
							</div>
							<canvas id="sectorPerformanceChart" height="265"></canvas>
						</div>
					</div>
				</div>
				<div class="col-md-6">		
					<div class="card">
						<div class="card-body">
							<?php if (!empty($earlySignals)): ?>
								<h5>Frühindikator: Potenzielle Sektorwenden</h5>
								<ul class="mb-0 list-group list-group-flush">
									<?php foreach ($earlySignals as $signal): ?>
										<li class="list-group-item px-0 bg-transparent">
											<span class="badge bg-warning text-white me-2"><?= $signal['type'] ?></span>
											<strong><?= htmlspecialchars($signal['sector']) ?>:</strong>
											<?= $signal['details'] ?>
										</li>
									<?php endforeach; ?>
								</ul>
							<?php endif; ?>
						</div>
					</div>
					<div class="card mt-3">
						<div class="card-body">
							<?php
							// Letzte 30 Tage extrahieren
							$historyDays = array_slice($history, -30, true);
							$sectorList = array_keys($todayPerf);
							
							$dates = array_keys($historyDays);
							
							$sectorSeries = [];
							foreach ($sectorList as $sector) {
								$sectorSeries[$sector] = [];
								foreach ($historyDays as $day => $dayData) {
									$val = $dayData[$sector] ?? null;
									$sectorSeries[$sector][] = is_numeric($val) ? round($val, 2) : null;
								}
							}
							?>
							
							<script>
								const sectorLineLabels = <?= json_encode($dates) ?>;
								const sectorLineDatasets = <?= json_encode(array_map(
									fn($name, $data) => [
										'label' => $name,
										'data' => $data,
										'fill' => false,
										'tension' => 0.3
									],
									array_keys($sectorSeries),
									array_values($sectorSeries)
								)) ?>;
							</script>
							<canvas id="sectorLineChart" height="200"></canvas>
						</div>
					</div>
				</div>
			</div>
			
			<div class="row mt-4">
				<div class="col-lg-12">
					<h6>Sektoren auswählen</h6>
					<ul class="list-group">
						<li class="list-group-item"><a href="https://finviz.com/groups.ashx" target="_blank" class="text-dark">https://finviz.com/groups.ashx</a></li>
						<li class="list-group-item"><a href="https://divvydiary.com/de/symbols" target="_blank" class="text-dark">https://divvydiary.com/de/symbols</a></li>
					</ul>
					<h5 class="mt-5 mb-3">Performance Sektoren in Phasen fallender Zinsen:</h5>
					<div class="table-responsive">
						<table class="table table-bordered align-middle">
						  <thead class="table-light">
							<tr>
							  <th>Sektor</th>
							  <th>Negativ</th>
							  <th>Positiv</th>
							</tr>
						  </thead>
						  <tbody>
							<tr>
							  <td>Nahrungsmittel, Getränke & Tabak</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 0px;"></div>0</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 130px;"></div>13</div></td>
							</tr>
							<tr>
							  <td>Körperpflege, Drogerie & Lebensmittelgeschäft</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 0px;"></div>0</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 130px;"></div>13</div></td>
							</tr>
							<tr>
							  <td>Gesundheit</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 10px;"></div>1</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 120px;"></div>12</div></td>
							</tr>
							<tr>
							  <td>Versorger</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 20px;"></div>2</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 110px;"></div>11</div></td>
							</tr>
							<tr>
							  <td>Einzelhandel</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 20px;"></div>2</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 110px;"></div>11</div></td>
							</tr>
							<tr>
							  <td>Konsumentenprodukte & -dienstleistungen</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 30px;"></div>3</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 100px;"></div>10</div></td>
							</tr>
							<tr>
							  <td>Immobilien</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 40px;"></div>4</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 90px;"></div>9</div></td>
							</tr>
							<tr>
							  <td>Telekommunikation</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 60px;"></div>6</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 70px;"></div>7</div></td>
							</tr>
							<tr>
							  <td>Versicherungen</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 60px;"></div>6</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 70px;"></div>7</div></td>
							</tr>
							<tr>
							  <td>Finanzdienstleistungen</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 60px;"></div>6</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 70px;"></div>7</div></td>
							</tr>
							<tr>
							  <td>Reisen und Freizeit</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 60px;"></div>6</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 70px;"></div>7</div></td>
							</tr>
							<tr>
							  <td>Chemie</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 70px;"></div>7</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 60px;"></div>6</div></td>
							</tr>
							<tr>
							  <td>Industriegüter und Dienstleistungen</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 80px;"></div>8</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 50px;"></div>5</div></td>
							</tr>
							<tr>
							  <td>Technologie</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 80px;"></div>8</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 50px;"></div>5</div></td>
							</tr>
							<tr>
							  <td>Automobilhersteller und Zulieferer</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 90px;"></div>9</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 40px;"></div>4</div></td>
							</tr>
							<tr>
							  <td>Bauwesen und Materialien</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 90px;"></div>9</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 40px;"></div>4</div></td>
							</tr>
							<tr>
							  <td>Medien</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 90px;"></div>9</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 40px;"></div>4</div></td>
							</tr>
							<tr>
							  <td>Banken</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 90px;"></div>9</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 40px;"></div>4</div></td>
							</tr>
							<tr>
							  <td>Energie</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 100px;"></div>10</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 30px;"></div>3</div></td>
							</tr>
							<tr>
							  <td>Rohstoffe</td>
							  <td><div class="bar-container"><div class="bar bar-negative" style="width: 110px;"></div>11</div></td>
							  <td><div class="bar-container"><div class="bar bar-positive" style="width: 20px;"></div>2</div></td>
							</tr>
						  </tbody>
						</table>
					</div>
				</div>
			</div>
		</div>
	</section>
</main>

<script>
const ctx = document.getElementById('sectorPerformanceChart').getContext('2d');

const datasetMap = {
	'Heute': {
		data: dataToday,
		backgroundColor: dataToday.map(v => v >= 0 ? 'rgba(40,167,69,0.6)' : 'rgba(220,53,69,0.6)'),
		borderColor: dataToday.map(v => v >= 0 ? 'rgba(40,167,69,1)' : 'rgba(220,53,69,1)')
	},
	'1 Woche': {
		data: data1w,
		backgroundColor: 'rgba(0,123,255,0.5)',
		borderColor: 'rgba(0,123,255,1)'
	},
	'1 Monat': {
		data: data1m,
		backgroundColor: 'rgba(255,193,7,0.5)',
		borderColor: 'rgba(255,193,7,1)'
	},
	'3 Monate': {
		data: data3m,
		backgroundColor: 'rgba(108,117,125,0.5)',
		borderColor: 'rgba(108,117,125,1)'
	},
	'6 Monate': {
		data: data6m,
		backgroundColor: 'rgba(23,162,184,0.5)',
		borderColor: 'rgba(23,162,184,1)'
	},
	'12 Monate': {
		data: data12m,
		backgroundColor: 'rgba(111,66,193,0.5)',
		borderColor: 'rgba(111,66,193,1)'
	}
};

const initialDatasets = ['1 Woche', '1 Monat'];

const chart = new Chart(ctx, {
	type: 'bar',
	data: {
		labels: sectorLabels,
		datasets: initialDatasets.map(label => ({
			label,
			data: datasetMap[label].data,
			backgroundColor: datasetMap[label].backgroundColor,
			borderColor: datasetMap[label].borderColor,
			borderWidth: 1
		}))
	},
	options: {
		indexAxis: 'y',
		responsive: true,
		scales: {
			x: {
				beginAtZero: true,
				title: {
					display: true,
					text: 'Performance (%)'
				}
			}
		},
		plugins: {
			title: {
				display: true,
				text: 'Sektor-Performance',
				color: '#000'
			},
			tooltip: {
				callbacks: {
					label: function(ctx) {
						const val = ctx.raw;
						const label = ctx.dataset.label;
						const i = ctx.dataIndex;
						let base = `${label}: ${val >= 0 ? '+' : ''}${val.toFixed(2)} %`;

						if (label === 'Heute' && dataYesterday[i] != null) {
							const diff = (val - dataYesterday[i]).toFixed(2);
							const change = diff >= 0 ? `▲ +${diff}` : `▼ ${diff}`;
							base += ` (vs. gestern: ${change} %)`;
						}

						return base;
					}
				}
			},
			legend: {
				position: 'bottom'
			}
		}
	}
});
</script>
<script>
document.querySelectorAll('#toggleButtons button').forEach(btn => {
	btn.addEventListener('click', () => {
		const label = btn.dataset.dataset;
		const datasetIndex = chart.data.datasets.findIndex(d => d.label === label);

		if (datasetIndex !== -1) {
			chart.data.datasets.splice(datasetIndex, 1);
			btn.classList.remove('active');
		} else {
			const data = datasetMap[label];
			chart.data.datasets.push({
				label,
				data: data.data,
				backgroundColor: data.backgroundColor,
				borderColor: data.borderColor,
				borderWidth: 1
			});
			btn.classList.add('active');
		}

		chart.update();
	});
});
</script>
<script>
const ctxLine = document.getElementById('sectorLineChart').getContext('2d');

new Chart(ctxLine, {
	type: 'line',
	data: {
		labels: sectorLineLabels,
		datasets: sectorLineDatasets.map((ds, i) => ({
			...ds,
			borderColor: `hsl(${(i * 30) % 360}, 70%, 50%)`,
			backgroundColor: `hsl(${(i * 30) % 360}, 70%, 50%)`,
			pointRadius: 2
		}))
	},
	options: {
		responsive: true,
		scales: {
			y: {
				title: {
					display: true,
					text: 'Tagesveränderung (%)'
				}
			},
			x: {
				title: {
					display: true,
					text: 'Datum'
				}
			}
		},
		plugins: {
			tooltip: {
				mode: 'nearest',
				intersect: false,
				callbacks: {
					label: ctx => `${ctx.dataset.label}: ${ctx.raw >= 0 ? '+' : ''}${ctx.raw.toFixed(2)} %`
				}
			},
			legend: {
				display: true,
				position: 'bottom',
				labels: {
					boxWidth: 12,
					usePointStyle: true
				}
			}
		}
	}
});
</script>

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