<?php require_once __DIR__ . '/engine/engine.php'; ?>
<?php require_once __DIR__ . '/engine/api-handling/api_helpers.php'; ?>
<?php require_once __DIR__ . '/views/header.php'; ?>
<?php require_once __DIR__ . '/views/navigation.php'; ?>

<main class="flex-grow-1">
	<section>
		<div class="container my-5">
	    	<div class="row">
				<div class="col-lg-12">
					<h4>JSON-Ticker-Listen erstellen:</h4>
					<ol class="mb-0">
						<li>Exchange-Liste laden und Symbole extrahieren: <a href="https://eodhd.com/api/exchanges-list/?api_token=<?= $EodhdApiKey ?>&fmt=json" target="_blank" class="text-dark">Liste bei EODHD downloaden</a></li>
						<li>Monats-Lizenz bei EOD Historical Data erwerben: <a href="https://eodhd.com" target="_blank" class="text-dark">https://eodhd.com</a></li>
						<li>Ticker-Listen downloaden bei EOD Historical Data (Steps schrittweise in URL erhöhen): <a href="execute/tickers/fetch_eodhd_tickers.php?step=0" class="text-dark">Download starten</a></li>
						<li>JSON Dateien in App-Daten austauschen</a></li>
					</ol>
				</div>
				
				<div class="col-lg-12 mt-5">
					<h4>JSON-Felder wählen & gefiltert herunterladen:</h4>
					<div class="card">
						<form id="jsonForm">
							<div class="card-body">
								<label for="jsonFileUpload" class="form-label">JSON-Datei auswählen</label>
								<input class="form-control" type="file" id="jsonFileUpload" accept=".json,application/json" />
							
								<div id="fileMeta" class="small text-muted d-none mb-2"></div>
							
								<div id="fieldChooser" class="mt-4 mb-3 d-none">
									<div class="mb-1">
										<h5 class="fw-bold">Felder auswählen</h5>
										<div class="form-check">
											<input class="form-check-input" type="checkbox" id="toggleAll" />
											<label class="form-check-label" for="toggleAll">Alle / Keine</label>
										</div>
									</div>
									<div class="alert bg-light row g-0 pb-2" id="checkboxGrid"></div>
								</div>
							
								<div id="previewWrap" class="d-none mt-4">
									<div class="mb-2 d-flex justify-content-between">
										<h5 class="fw-bold">Vorschau <small id="previewCount" class="text-muted"></small></h5>
										<button id="downloadBtn" type="button" class="btn btn-dark btn-sm" disabled>
											Gefilterte JSON herunterladen
										</button>
									</div>
									<div class="table-responsive small">
										<table class="table table-sm table-striped align-middle" id="previewTable">
											<thead></thead>
											<tbody></tbody>
										</table>
									</div>
								</div>
							</div>
						</form>
						<div id="alertContainer"></div>
					</div>
				</div>
				
				<div class="col-lg-12 mt-5">
					<h4>JSON-Ticker-Listen einsehen:</h4>
					<div class="card">
						<div class="card-body">
							<?php
							$selected = $_GET['symbol'] ?? null;
							
							$downloadsDir = __DIR__ . "/execute/tickers/ticker-listen/";
							$tickerFiles = glob($downloadsDir . "*.json");
							
							$tickerData = [];
							
							foreach ($tickerFiles as $path) {
								$ticker = basename($path, ".json");
								$json = file_get_contents($path);
								$data = json_decode($json, true);
								$count = is_array($data) ? count($data) : 0;
							
								$tickerData[] = [
									'name' => $ticker,
									'count' => $count
								];
							}
							
							usort($tickerData, function ($a, $b) {
								return strcmp($a['name'], $b['name']);
							});
							?>
							
							<h5>Vorschau Ticker-Listen als JSON (<?= count($tickerFiles) ?>)</h5>
							<form method="GET" class="mt-3">
								<label for="symbol" class="form-label">Datei auswählen:</label>
								<select name="symbol" id="symbol" class="form-select" onchange="this.form.submit()">
								<option value="">-- Bitte wählen --</option>
								<?php foreach ($tickerData as $item): ?>
									<option value="<?= htmlspecialchars($item['name']) ?>" <?= ($item['name'] === $selected) ? 'selected' : '' ?>>
									<?= htmlspecialchars($item['name']) ?> (<?= $item['count'] ?> Einträge)
									</option>
								<?php endforeach; ?>
								</select>
							</form>
							
							<?php
							if ($selected) {
								$filepath = $downloadsDir . $selected . ".json";
								if (file_exists($filepath)) {
									$json = file_get_contents($filepath);
									$data = json_decode($json, true);
							
									if (json_last_error() === JSON_ERROR_NONE) {
										echo "<h2>Inhalt von <code>{$selected}.json</code>:</h2>";
										echo "<pre>" . json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "</pre>";
									} else {
										echo "<p style='color:red;'>Fehler beim Parsen der JSON-Datei.</p>";
									}
								} else {
									echo "<p style='color:red;'>Datei nicht gefunden: {$filepath}</p>";
								}
							}
							?>
						</div>
					</div>
				</div>
				
				<div class="col-lg-12 mt-2">
					<div class="card">
						<div class="card-body">
							<h5>Vorschau Ticker-Listen als Tabelle (<?= count($tickerFiles) ?>)</h5>			
							<?php $files = glob(__DIR__ . "/execute/tickers/ticker-listen/*.json"); ?>
							<label for="tickerSelect" class="form-label">Datei auswählen:</label>
							<select id="tickerSelect" class="form-select">
							<option value="">-- Bitte wählen --</option>
							<?php foreach ($files as $file): ?>
								<?php $basename = basename($file, '.json'); ?>
								<option value="<?= htmlspecialchars($basename) ?>"><?= htmlspecialchars($basename) ?></option>
							<?php endforeach; ?>
							</select>
							<div id="preview" class="d-none mt-3"></div>
						</div>
					</div>
				</div>
				
				<div class="col-lg-12 mt-5">
					<h4>JSON-Ticker-Listen filtern:</h4>
					<div class="card">
						<div class="card-body">
							<h5>Nach fundamentalem Schwellenwert filtern:</h5>
							<form action="" method="post" enctype="multipart/form-data">
								<div class="mb-3">
								<label for="jsonFile" class="form-label">JSON-Datei hochladen</label>
								<input type="file" class="form-control" name="jsonFile" id="jsonFile" accept=".json" required>
								</div>
						
								<div class="mb-3">
								<label for="threshold" class="form-label">Score-Schwellenwert (0–100)</label>
								<input type="number" class="form-control" name="threshold" id="threshold" min="0" max="100" placeholder="90" required>
								</div>
								
								<div class="mb-3">
								<label for="filename" class="form-label">Dateiname (optional, ohne .json)</label>
								<input type="text" class="form-control" name="filename" id="filename" placeholder="mein_export">
								</div>
						
								<button type="submit" class="btn btn-dark w-100">Filtern und Datei erzeugen</button>
							</form>
							<?php
							if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['jsonFile'])) {
								$threshold = isset($_POST['threshold']) ? intval($_POST['threshold']) : 0;
								$filename = isset($_POST['filename']) ? $_POST['filename'] : '';
								$filename = preg_replace('/[^a-zA-Z0-9_-]/', '', $filename);
								if ($filename === '') {
									$filename = 'filtered_' . time();
								}
								$customName = $filename . '.json';
							
								$upload = $_FILES['jsonFile'];
								if ($upload['error'] !== UPLOAD_ERR_OK) {
									echo '<div class="alert alert-danger mt-4">Fehler beim Hochladen der Datei.</div>';
								} else {
									$jsonData = file_get_contents($upload['tmp_name']);
									$data = json_decode($jsonData, true);
							
									if (is_array($data)) {
										$filtered = array_filter($data, function ($e) use ($threshold) {
											return isset($e['Score']) && floatval($e['Score']) >= $threshold;
										});
							
										$savePath = __DIR__ . '/execute/tickers/ticker-listen/' . $customName;
										file_put_contents($savePath, json_encode(array_values($filtered), JSON_PRETTY_PRINT));
							
										$count = count($filtered);
										echo <<<HTML
							<div class="alert alert-success mt-4">
							  <strong>Filter erfolgreich:</strong> $count Einträge mit Score ≥ $threshold gefunden.<br>
							  JSON-File wurde im Ordner Tickers gespeichert.<br>
							</div>
							HTML;
									} else {
										echo '<div class="alert alert-danger mt-4">Ungültige oder nicht verarbeitbare JSON-Datei.</div>';
									}
								}
							}
							?>
						</div>
					</div>
				</div>
				
				<div class="col-lg-12 mt-5">
					<h4>FMP-Listen:</h4>
					<?php
					echo '<h6>Fundamentals:</h6>';
					echo '<ul class="list-group">';
					$endpoints = [
						'Company Profile' => "https://financialmodelingprep.com/api/v3/profile/AAPL?apikey=$FmpApiKey",
						'Company Key Metrics' => "https://financialmodelingprep.com/api/v3/key-metrics/AAPL?apikey=$FmpApiKey",
						'Company Ratios' => "https://financialmodelingprep.com/api/v3/ratios/AAPL?apikey=$FmpApiKey",
						'Company Rating' => "https://financialmodelingprep.com/api/v3/rating/AAPL?apikey=$FmpApiKey",
						'Financial Statements (Income Statement)' => "https://financialmodelingprep.com/api/v3/income-statement/AAPL?apikey=$FmpApiKey",
						'Balance Sheet' => "https://financialmodelingprep.com/api/v3/balance-sheet-statement/AAPL?apikey=$FmpApiKey",
						'Cash Flow Statement' => "https://financialmodelingprep.com/api/v3/cash-flow-statement/AAPL?apikey=$FmpApiKey",
						'Enterprise Value' => "https://financialmodelingprep.com/api/v3/enterprise-values/AAPL?apikey=$FmpApiKey",
						'Financial Growth' => "https://financialmodelingprep.com/api/v3/financial-growth/AAPL?apikey=$FmpApiKey",
						'DCF (Discounted Cash Flow)' => "https://financialmodelingprep.com/api/v3/discounted-cash-flow/AAPL?apikey=$FmpApiKey",
						'Stock Screener' => "https://financialmodelingprep.com/api/v3/stock-screener?apikey=$FmpApiKey",
					];
					foreach ($endpoints as $label => $url) {
						echo '<li class="list-group-item"><a href="'.$url.'" class="text-dark" target="_blank">'.$label.'</a></li>';
					}
					echo '</ul>';
					?>
					
					<?php
					echo '<h6 class="mt-4">Market Data:</h6>';
					echo '<ul class="list-group">';
					$endpoints = [
						'Real-Time Quote (Single)' => "https://financialmodelingprep.com/api/v3/quote/AAPL?apikey=$FmpApiKey",
						'Real-Time Quote (Multiple)' => "https://financialmodelingprep.com/api/v3/quote/AAPL,MSFT,GOOGL?apikey=$FmpApiKey",
						'Market Movers – Gainers' => "https://financialmodelingprep.com/api/v3/stock_market/gainers?apikey=$FmpApiKey",
						'Market Movers – Losers' => "https://financialmodelingprep.com/api/v3/stock_market/losers?apikey=$FmpApiKey",
						'Market Movers – Actives' => "https://financialmodelingprep.com/api/v3/stock_market/actives?apikey=$FmpApiKey",
						'Historical Price (Full)' => "https://financialmodelingprep.com/api/v3/historical-price-full/AAPL?apikey=$FmpApiKey",
						'Historical Chart (1min, 5min, 15min, 30min, 1h)' => "https://financialmodelingprep.com/api/v3/historical-chart/1min/AAPL?apikey=$FmpApiKey",
						'Stock Dividend History' => "https://financialmodelingprep.com/api/v3/historical-price-full/stock_dividend/AAPL?apikey=$FmpApiKey",
						'Stock Split History' => "https://financialmodelingprep.com/api/v3/historical-price-full/stock_split/AAPL?apikey=$FmpApiKey",
						'Volume Profile' => "https://financialmodelingprep.com/api/v3/volume-profile/AAPL?apikey=$FmpApiKey",
						'Delisted Companies' => "https://financialmodelingprep.com/api/v3/delisted-companies?apikey=$FmpApiKey",
						'Search Symbol' => "https://financialmodelingprep.com/api/v3/search?query=apple&limit=10&exchange=NASDAQ&apikey=$FmpApiKey",
					];
					foreach ($endpoints as $label => $url) {
						echo '<li class="list-group-item"><a href="'.$url.'" class="text-dark" target="_blank">'.$label.'</a></li>';
					}
					echo '</ul>';
					?>
					
					<?php
					echo '<h6 class="mt-4">ETFs & Funds:</h6>';
					echo '<ul class="list-group">';
					$endpoints = [
						'ETF Symbols List' => "https://financialmodelingprep.com/api/v3/etf/list?apikey=$FmpApiKey",
						'ETF Quote' => "https://financialmodelingprep.com/api/v3/quote/ETF_SYMBOL?apikey=$FmpApiKey",
						'Fund Holdings' => "https://financialmodelingprep.com/api/v3/etf-holders/ETF_SYMBOL?apikey=$FmpApiKey",
						'Fund Performance' => "https://financialmodelingprep.com/api/v3/etf/ETF_SYMBOL?apikey=$FmpApiKey",
						'Mutual Funds List' => "https://financialmodelingprep.com/api/v3/mutual-fund/list?apikey=$FmpApiKey",
						'Mutual Fund Quote' => "https://financialmodelingprep.com/api/v3/quote/MUTUALFUND_SYMBOL?apikey=$FmpApiKey",
						'Mutual Fund Profile' => "https://financialmodelingprep.com/api/v3/mutual-fund/profile/MUTUALFUND_SYMBOL?apikey=$FmpApiKey",
						'ETF Volume Profile' => "https://financialmodelingprep.com/api/v3/volume-profile/ETF_SYMBOL?apikey=$FmpApiKey",
					];
					foreach ($endpoints as $label => $url) {
						echo '<li class="list-group-item"><a href="' . $url . '" class="text-dark" target="_blank">' . $label . '</a></li>';
					}
					echo '</ul>';
					?>
					
					<?php
					echo '<h6 class="mt-4">Forex & Crypto:</h6>';
					echo '<ul class="list-group">';
					$endpoints = [
						// Forex
						'Available Forex Pairs' => "https://financialmodelingprep.com/api/v3/symbol/available-forex-currency-pairs?apikey=$FmpApiKey",
						'Forex Quotes (All)' => "https://financialmodelingprep.com/api/v3/quotes/forex?apikey=$FmpApiKey",
						
						// Crypto
						'Available Cryptocurrencies' => "https://financialmodelingprep.com/api/v3/symbol/available-cryptocurrencies?apikey=$FmpApiKey",
						'Crypto Quotes (All)' => "https://financialmodelingprep.com/api/v3/quotes/crypto?apikey=$FmpApiKey",
					];
					foreach ($endpoints as $label => $url) {
						echo '<li class="list-group-item"><a href="' . $url . '" class="text-dark" target="_blank">' . $label . '</a></li>';
					}
					echo '</ul>';
					?>
					
					<?php
					echo '<h6 class="mt-4">Analyst Ratings, Sentiment & News:</h6>';
					echo '<ul class="list-group">';
					$endpoints = [
						// Analysten & Bewertungen
						'Analyst Ratings (Recommendations)' => "https://financialmodelingprep.com/api/v3/analyst-stock-recommendations/AAPL?apikey=$FmpApiKey",
						'Price Target' => "https://financialmodelingprep.com/api/v3/price-target/AAPL?apikey=$FmpApiKey",
						'Stock Grade (A–F Rating)' => "https://financialmodelingprep.com/api/v3/grade/AAPL?apikey=$FmpApiKey",
					
						// News & Presse
						'Company Press Releases' => "https://financialmodelingprep.com/api/v3/press-releases/AAPL?apikey=$FmpApiKey",
						'Stock News (alle)' => "https://financialmodelingprep.com/api/v3/stock_news?limit=50&apikey=$FmpApiKey",
					
						// Sentiment & ESG
						'Social Sentiment (Twitter, Reddit, News)' => "https://financialmodelingprep.com/api/v4/social-sentiment/AAPL?apikey=$FmpApiKey",
						'ESG Rating (Environmental, Social, Governance)' => "https://financialmodelingprep.com/api/v4/esg-environmental-social-governance/AAPL?apikey=$FmpApiKey",
					];
					foreach ($endpoints as $label => $url) {
						echo '<li class="list-group-item"><a href="' . $url . '" class="text-dark" target="_blank">' . $label . '</a></li>';
					}
					echo '</ul>';
					?>
					
					<?php
					echo '<h6 class="mt-4">Macro & Economic Data:</h6>';
					echo '<ul class="list-group">';
					$endpoints = [
						'Treasury Yield Curve (All)' => "https://financialmodelingprep.com/api/v3/treasury?apikey=$FmpApiKey",
						'10Y Treasury Rate (Historical)' => "https://financialmodelingprep.com/api/v3/10-year-treasury-rate?apikey=$FmpApiKey",
						'2Y Treasury Rate (Historical)' => "https://financialmodelingprep.com/api/v3/2-year-treasury-rate?apikey=$FmpApiKey",
						'Fed Funds Rate' => "https://financialmodelingprep.com/api/v3/fed-funds-rate?apikey=$FmpApiKey",
						'Inflation Rate (USA)' => "https://financialmodelingprep.com/api/v3/inflation?apikey=$FmpApiKey",
						'CPI (Consumer Price Index)' => "https://financialmodelingprep.com/api/v3/cpi?apikey=$FmpApiKey",
						'Real GDP (USA)' => "https://financialmodelingprep.com/api/v3/real-gdp?apikey=$FmpApiKey",
						'Nominal GDP (USA)' => "https://financialmodelingprep.com/api/v3/nominal-gdp?apikey=$FmpApiKey",
						'GDP per Capita' => "https://financialmodelingprep.com/api/v3/gdp-per-capita?apikey=$FmpApiKey",
						'Unemployment Rate (USA)' => "https://financialmodelingprep.com/api/v3/unemployment-rate?apikey=$FmpApiKey",
						'US Consumer Sentiment' => "https://financialmodelingprep.com/api/v3/consumer-sentiment?apikey=$FmpApiKey",
						'US Imports' => "https://financialmodelingprep.com/api/v3/us-imports?apikey=$FmpApiKey",
						'US Exports' => "https://financialmodelingprep.com/api/v3/us-exports?apikey=$FmpApiKey",
						'Recession Probabilities' => "https://financialmodelingprep.com/api/v3/recession-probabilities?apikey=$FmpApiKey",
						'Economic Indicators List' => "https://financialmodelingprep.com/api/v3/economic_calendar?apikey=$FmpApiKey"
					];
					foreach ($endpoints as $label => $url) {
						echo '<li class="list-group-item"><a href="' . $url . '" class="text-dark" target="_blank">' . $label . '</a></li>';
					}
					echo '</ul>';
					?>
					
					<?php
					echo '<h6 class="mt-4">Index Constituents & Symbol Lists:</h6>';
					echo '<ul class="list-group">';
					$endpoints = [
						// Indizes
						'S&P 500 Constituents' => "https://financialmodelingprep.com/api/v3/sp500_constituent?apikey=$FmpApiKey",
						'NASDAQ 100 Constituents' => "https://financialmodelingprep.com/api/v3/nasdaq_constituent?apikey=$FmpApiKey",
						'Dow Jones Constituents' => "https://financialmodelingprep.com/api/v3/dowjones_constituent?apikey=$FmpApiKey",
					
						// Symbol- & Exchange-Listen
						'All Listed Stocks' => "https://financialmodelingprep.com/api/v3/stock/list?apikey=$FmpApiKey",
						'Delisted Companies' => "https://financialmodelingprep.com/api/v3/delisted-companies?apikey=$FmpApiKey",
						'Available Exchanges' => "https://financialmodelingprep.com/api/v3/exchanges-list?apikey=$FmpApiKey",
						'All ETFs' => "https://financialmodelingprep.com/api/v3/etf/list?apikey=$FmpApiKey",
						'All Mutual Funds' => "https://financialmodelingprep.com/api/v3/mutual-fund/list?apikey=$FmpApiKey",
					
						// Sektoren & Branchen
						'Sectors List' => "https://financialmodelingprep.com/api/v3/sectors-list?apikey=$FmpApiKey",
						'Industries List' => "https://financialmodelingprep.com/api/v3/industries-list?apikey=$FmpApiKey",
					
						// Suchfunktion
						'Search by Name / Symbol' => "https://financialmodelingprep.com/api/v3/search?query=apple&limit=10&exchange=NASDAQ&apikey=$FmpApiKey",
						'Search Ticker Autocomplete' => "https://financialmodelingprep.com/api/v3/search-ticker?query=tesla&apikey=$FmpApiKey",
					];
					foreach ($endpoints as $label => $url) {
						echo '<li class="list-group-item"><a href="' . $url . '" class="text-dark" target="_blank">' . $label . '</a></li>';
					}
					echo '</ul>';
					?>
					
					<?php
					echo '<h6 class="mt-4">Weitere APIs:</h6>';
					echo '<ul class="list-group">';
					$endpoints = [
						// Unternehmensstruktur & Management
						'Key Executives' => "https://financialmodelingprep.com/api/v3/key-executives/AAPL?apikey=$FmpApiKey",
						'Company Employees' => "https://financialmodelingprep.com/api/v4/company-employees/AAPL?apikey=$FmpApiKey",
						
						// Eigentümer & Beteiligungen
						'Institutional Ownership' => "https://financialmodelingprep.com/api/v4/institutional-ownership/symbol-ownership?symbol=AAPL&apikey=$FmpApiKey",
						'ETF Holdings for Stock' => "https://financialmodelingprep.com/api/v4/etf-stock-exposure?symbol=AAPL&apikey=$FmpApiKey",
						'Stock Holdings in ETF' => "https://financialmodelingprep.com/api/v4/etf-holdings?symbol=SPY&apikey=$FmpApiKey",
					
						// IPOs
						'Upcoming IPOs' => "https://financialmodelingprep.com/api/v3/ipo_calendar?apikey=$FmpApiKey",
					
						// Insider-Transaktionen
						'Insider Trading (all)' => "https://financialmodelingprep.com/api/v4/insider-trading?apikey=$FmpApiKey",
						'Congress Trading (all)' => "https://financialmodelingprep.com/api/v4/congress-trading?apikey=$FmpApiKey",
					
						// Presse & News
						'SEC Filings (10-K, 10-Q)' => "https://financialmodelingprep.com/api/v3/sec_filings/AAPL?apikey=$FmpApiKey",
						'8-K Filings (Company Events)' => "https://financialmodelingprep.com/api/v3/sec_8k_filings/AAPL?apikey=$FmpApiKey",
					
						// Bewertungen & Governance
						'ESG Score (v4)' => "https://financialmodelingprep.com/api/v4/esg-environmental-social-governance/AAPL?apikey=$FmpApiKey",
						'Company Grade (A–F Rating)' => "https://financialmodelingprep.com/api/v3/grade/AAPL?apikey=$FmpApiKey",
					
						// Kalender & Ereignisse
						'Earnings Calendar' => "https://financialmodelingprep.com/api/v3/earning_calendar?apikey=$FmpApiKey",
						'Economic Calendar' => "https://financialmodelingprep.com/api/v3/economic_calendar?apikey=$FmpApiKey",
					
						// Technische Zusatzinfos
						'Delisted Companies' => "https://financialmodelingprep.com/api/v3/delisted-companies?apikey=$FmpApiKey",
					];
					foreach ($endpoints as $label => $url) {
						echo '<li class="list-group-item"><a href="' . $url . '" class="text-dark" target="_blank">' . $label . '</a></li>';
					}
					echo '</ul>';

					?>
				</div>
			</div>
		</div>
    </section>
</main>

<script>
$('#tickerSelect').on('change', function () {
  const list = $(this).val();

  if (!list) {
	$('#preview').addClass('d-none').html('');
	return;
  }

  $.get('execute/tickers/load_tickers.php?list=' + encodeURIComponent(list), function (html) {
	$('#preview').html(html).removeClass('d-none');
	$('#tickerTable').DataTable();
  });
});
</script>

<script>
(function(){
  function initJSONTool(){
	const jsonFileInput = document.getElementById('jsonFileUpload');
	const fieldChooser   = document.getElementById('fieldChooser');
	const checkboxGrid   = document.getElementById('checkboxGrid');
	const previewWrap    = document.getElementById('previewWrap');
	const previewTable   = document.getElementById('previewTable');
	const previewCount   = document.getElementById('previewCount');
	const downloadBtn    = document.getElementById('downloadBtn');
	const toggleAll      = document.getElementById('toggleAll');
	const alertContainer = document.getElementById('alertContainer');
	const fileMeta       = document.getElementById('fileMeta');

	if (!jsonFileInput) {
	  console.error('Input #jsonFileUpload nicht gefunden');
	  return;
	}

	let originalData = null;     // Array von Objekten
	let allKeys = [];            // Gesamte Schlüsselliste
	let selectedKeys = new Set();// Ausgewählte Schlüssel
	let originalFilename = 'data.json';

	function safeId(text) {
	  return 'check_' + String(text).replace(/[^a-zA-Z0-9_-]/g, '_');
	}

	function showAlert(type, message) {
	  alertContainer.innerHTML = `
		<div class="alert alert-${type} alert-dismissible fade show" role="alert">
		  ${message}
		  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
		</div>`;
	}

	function resetUI() {
	  fieldChooser.classList.add('d-none');
	  previewWrap.classList.add('d-none');
	  checkboxGrid.innerHTML = '';
	  previewTable.querySelector('thead').innerHTML = '';
	  previewTable.querySelector('tbody').innerHTML = '';
	  previewCount.textContent = '';
	  downloadBtn.disabled = true;
	  toggleAll.checked = false;
	  allKeys = [];
	  selectedKeys.clear();
	  originalData = null;
	  fileMeta.classList.add('d-none');
	  fileMeta.textContent = '';
	}

	function ensureArrayOfObjects(json) {
	  if (Array.isArray(json)) {
		if (json.length === 0) return [];
		return json.filter(item => item && typeof item === 'object' && !Array.isArray(item));
	  }
	  if (json && typeof json === 'object' && !Array.isArray(json)) {
		return [json];
	  }
	  return null;
	}

	function collectAllKeys(dataArr) {
	  const keySet = new Set();
	  dataArr.forEach(obj => Object.keys(obj).forEach(k => keySet.add(k)));
	  return Array.from(keySet).sort((a,b) => a.localeCompare(b));
	}

	function renderCheckboxes(keys) {
	  checkboxGrid.innerHTML = '';
	  const frag = document.createDocumentFragment();
	  selectedKeys.clear();
	  keys.forEach(key => {
		const col = document.createElement('div');
		col.className = 'col-12 col-sm-6 col-md-4 col-lg-3';
		const id = safeId(key);
		col.innerHTML = `
		  <div class="form-check">
			<input class="form-check-input field-check" type="checkbox" value="${key}" id="${id}" checked>
			<label class="form-check-label" for="${id}">${key}</label>
		  </div>`;
		frag.appendChild(col);
		selectedKeys.add(key);
	  });
	  checkboxGrid.appendChild(frag);
	  fieldChooser.classList.remove('d-none');
	  toggleAll.checked = true;

	  checkboxGrid.querySelectorAll('.field-check').forEach(cb => {
		cb.addEventListener('change', () => {
		  if (cb.checked) selectedKeys.add(cb.value); else selectedKeys.delete(cb.value);
		  toggleAll.checked = (selectedKeys.size === allKeys.length);
		  updatePreview();
		});
	  });
	}

	function updatePreview() {
	  if (!originalData) return;
	  const keys = Array.from(selectedKeys);

	  const thead = previewTable.querySelector('thead');
	  thead.innerHTML = '';
	  const trHead = document.createElement('tr');
	  keys.forEach(k => {
		const th = document.createElement('th');
		th.textContent = k;
		trHead.appendChild(th);
	  });
	  thead.appendChild(trHead);

	  const tbody = previewTable.querySelector('tbody');
	  tbody.innerHTML = '';
	  const maxRows = Math.min(50, originalData.length);
	  for (let i = 0; i < maxRows; i++) {
		const row = document.createElement('tr');
		keys.forEach(k => {
		  const td = document.createElement('td');
		  let val = originalData[i]?.[k];
		  if (val === undefined) val = '';
		  if (typeof val === 'object') {
			try { val = JSON.stringify(val); } catch (e) { val = String(val); }
		  }
		  td.textContent = val;
		  row.appendChild(td);
		});
		tbody.appendChild(row);
	  }

	  previewCount.textContent = `(${originalData.length} Zeilen, ${keys.length} Spalten)`;
	  downloadBtn.disabled = keys.length === 0;
	  previewWrap.classList.remove('d-none');
	}

	function buildFilteredData() {
	  const keys = Array.from(selectedKeys);
	  return originalData.map(obj => {
		const out = {};
		keys.forEach(k => { if (Object.prototype.hasOwnProperty.call(obj, k)) out[k] = obj[k]; });
		return out;
	  });
	}

	function triggerDownload(data, filename) {
	  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
	  const url = URL.createObjectURL(blob);
	  const a = document.createElement('a');
	  a.href = url;
	  a.download = filename;
	  document.body.appendChild(a);
	  a.click();
	  URL.revokeObjectURL(url);
	  a.remove();
	}

	jsonFileInput.addEventListener('change', (e) => {
	  resetUI();
	  alertContainer.innerHTML = '';

	  const file = e.target.files && e.target.files[0];
	  if (!file) return;
	  originalFilename = file.name || 'data.json';
	  const reader = new FileReader();
	  reader.onload = () => {
		try {
		  const json = JSON.parse(reader.result);
		  const arr = ensureArrayOfObjects(json);
		  if (arr === null) {
			showAlert('danger', 'Die Datei muss ein JSON-Objekt oder ein Array von Objekten enthalten.');
			return;
		  }
		  if (arr.length === 0) {
			showAlert('warning', 'Die JSON-Datei enthält keine verwertbaren Objekte.');
		  }
		  originalData = arr;
		  allKeys = collectAllKeys(arr);
		  if (allKeys.length === 0) {
			showAlert('warning', 'Keine Felder gefunden.');
			return;
		  }

		  fileMeta.textContent = `Geladen: ${originalFilename} · ${arr.length} Zeilen · ${allKeys.length} Felder`;
		  fileMeta.classList.remove('d-none');

		  renderCheckboxes(allKeys);
		  updatePreview();
		} catch (err) {
		  console.error(err);
		  showAlert('danger', 'Fehler beim Lesen der JSON-Datei: ' + (err && err.message ? err.message : err));
		}
	  };
	  reader.onerror = () => {
		showAlert('danger', 'Die Datei konnte nicht gelesen werden.');
	  };
	  reader.readAsText(file);
	});

	toggleAll.addEventListener('change', () => {
	  const check = toggleAll.checked;
	  selectedKeys.clear();
	  checkboxGrid.querySelectorAll('.field-check').forEach(cb => {
		cb.checked = check;
		if (check) selectedKeys.add(cb.value);
	  });
	  updatePreview();
	});

	downloadBtn.addEventListener('click', () => {
	  if (!originalData) return;
	  const filtered = buildFilteredData();
	  const base = originalFilename.replace(/\.json$/i, '');
	  const fname = `${base}-filtered.json`;
	  triggerDownload(filtered, fname);
	});
  }

  if (document.readyState === 'loading') {
	document.addEventListener('DOMContentLoaded', initJSONTool);
  } else {
	initJSONTool();
  }
})();
</script>

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