<?php include 'engine/engine.php'; ?>
<?php include 'views/header.php'; ?>
<?php include 'views/navigation.php'; ?>

<main>
	<section>
		<div class="container my-5">
			<div class="row">
				<div class="col-lg-12 mb-5">
					<?php
					
					set_time_limit(0);
					ini_set('memory_limit', '512M');
					
					$token = "6866ca25776f34.88331540";
					$exchangeCodes = [
						"NYSE",     // New York Stock Exchange
						"NASDAQ",   // Nasdaq Global Select/Market
						"NYSE MKT", // Früher AMEX, heute NYSE American – Mid- und Small-Caps
						"BATS",		// BATS Global Markets – oft parallele Listings, aber liquide
						"LSE",     // London Stock Exchange
						"XETRA",   // Deutsche Börse
						"PA",      // Euronext Paris
						"AS",      // Euronext Amsterdam
						"SW",      // SIX Swiss Exchange
						"BR",      // Euronext Brussels
						"MC",      // Madrid Exchange
						"AU",      // Australian Securities Exchange
						"HK",      // Hong Kong Exchange (nicht in der Datei enthalten, aber unterstützt)
						"NSE",     // National Stock Exchange of India
						"SA"       // Bovespa (Brasilien, große Werte wie Petrobras)
					];
					$manualMap = [
						"NYSE MKT" => "NYSE%20MKT"
					];
					
					// Anzahl Börsen pro Durchlauf (Batchgröße)
					$batchSize = 3;
					$step = isset($_GET['step']) ? (int)$_GET['step'] : 0;
					$start = $step * $batchSize;
					
					// automatische Weiterleitung einfügen
					$totalExchanges = 16; // Gesamtzahl deiner Exchanges
					$totalSteps = ceil($totalExchanges / $batchSize);
					
					if ($step + 1 < $totalSteps) {
						$nextStep = $step + 1;
						echo "<meta http-equiv='refresh' content='5;url=?step={$nextStep}'>";
					}
					
					// Lade optionalen Schritt-Parameter aus der URL
					$step = isset($_GET['step']) ? (int)$_GET['step'] : 0;
					
					// Berechne Startposition und schneide die Liste zu
					$start = $step * $batchSize;
					$exchangeCodes = array_slice($exchangeCodes, $start, $batchSize);
					
					// Hinweis anzeigen
					echo "<p>Batch <strong>$step</strong>: Lade Exchanges " . implode(", ", $exchangeCodes) . "</p>";
					
					$baseUrl = "https://eodhd.com/api/exchange-symbol-list/";
					$saveDir = __DIR__ . "/ticker-listen/";
					
					if (!is_dir($saveDir)) {
						mkdir($saveDir, 0755, true);
					}
					
					$skipped = [];
					$downloaded = [];
					$failed = [];
					
					foreach ($exchangeCodes as $code) {
						$filename = str_replace(" ", "_", $code) . ".json";
						$fullpath = $saveDir . $filename;
					
						if (file_exists($fullpath) && filesize($fullpath) > 100) {
							$skipped[] = $code;
							continue;
						}
					
						$encodedCode = isset($manualMap[$code]) ? $manualMap[$code] : urlencode($code);
						$url = "{$baseUrl}{$encodedCode}?type=common_stock&api_token={$token}&fmt=json";

						echo "Lade <strong>{$code}</strong>... ";
					
						$context = stream_context_create(['http' => ['timeout' => 15]]);
						$json = file_get_contents($url, false, $context);
						
						file_put_contents("log.txt", "Starte Download: {$url}\n", FILE_APPEND);
						
						if ($json === false) {
							$error = error_get_last();
							echo "<pre>Fehler beim Laden von: {$url}</pre>";
							echo "<pre>" . print_r($error, true) . "</pre>";
							continue;
						}
					
						if ($json === false || strlen($json) < 100) {
							echo "<span style='color:red;'>Fehlgeschlagen</span><br>";
							$failed[] = $code;
						} else {
							file_put_contents($fullpath, $json);
							echo "Gespeichert als <code>tickers/{$filename}</code><br>";
							$downloaded[] = $code;
						}
					
						sleep(2);
					}
					
					echo "<hr>";
					echo "<strong>Fertig!</strong><br>";
					echo "Neu heruntergeladen: " . count($downloaded) . "<br>";
					echo "Übersprungen (bereits vorhanden): " . count($skipped) . "<br>";
					echo "Fehlgeschlagen: " . count($failed) . "<br>";
					
					if (!empty($failed)) {
						echo "<br><strong>Fehlgeschlagene Exchanges:</strong><br><ul>";
						foreach ($failed as $fail) {
							echo "<li>{$fail}</li>";
						}
						echo "</ul>";
					}
					
					echo "<hr><strong>Fehlende Dateien überprüfen…</strong><br>";
					
					$expectedCount = count($exchangeCodes);
					$saveDir = __DIR__ . "/tickers/";
					$missing = [];
					
					foreach ($exchangeCodes as $code) {
						if ($code === "MONEY") continue; // bewusst entfernt
						$filename = str_replace(" ", "_", $code) . ".json";
						$fullpath = $saveDir . $filename;
					
						if (!file_exists($fullpath) || filesize($fullpath) < 100) {
							$missing[] = $code;
						}
					}
					
					echo "Erwartet: {$expectedCount} Dateien<br>";
					echo "Vorhanden: " . ($expectedCount - count($missing)) . "<br>";
					echo "Fehlende oder leere Dateien: " . count($missing) . "<br>";
					
					if (!empty($missing)) {
						echo "<ul>";
						foreach ($missing as $code) {
							echo "<li>{$code}</li>";
						}
						echo "</ul>";
					} else {
						echo "Alle Dateien vorhanden!";
					}
					
					?>
					<br><br><a href="../../tickers.php">Zurück zu den Tickern</a>
				</div>
			</div>
		</div>
	</section>
</main>
