<?php
$symbol = $GLOBALS['tab_symbol'] ?? '';
$asof   = $GLOBALS['tab_asof'] ?? null;
$target_pe = $GLOBALS['tab_target_pe'] ?? null;

require_once __DIR__ . '/../../engine/translation/translate_helper.php';
require_once __DIR__ . '/../../engine/api-handling/fmp_client.php';

$data = [];
// --- FMP data via fmp_client.php (reines Daten-Wiring, keine Logik-Änderung) ---
try {
	if (!isset($symbol) || !$symbol) {
		throw new \RuntimeException('Symbol fehlt.');
	}
	if (!function_exists('fmp_multi')) {
		throw new \RuntimeException('fmp_multi() nicht verfügbar – bitte fmp_client.php einbinden.');
	}

	$resp = fmp_multi([
		'profile' => ['key' => 'profile', 'vars' => ['symbol' => $symbol]],
	], 12);

	// Falls der Endpoint ein Array mit einem Eintrag liefert:
	$profile_data = $resp['profile'] ?? [];
	if (isset($profile_data[0]) && is_array($profile_data[0])) {
		$profile_data = $profile_data[0];
	}

	// Kompatibel befüllen: $data['raw']['profile'] und Index [0] für bestehende Zugriffe,
	// zudem $profile als direkte Referenz, falls vorhanden.
	$data['raw']['profile'] = $profile_data;
	$data['raw']['profile'][0] = $profile_data;
	if (!isset($profile) || !is_array($profile)) {
		$profile = $profile_data;
	}
} catch (\Throwable $ex) {
	error_log('[tab_profile] FMP Fetch Error: ' . $ex->Message());
}
// --- End Daten-Wiring ---


$profile = $data['raw']['profile'][0] ?? [];

function format_currency($value, $currency = 'USD') {
	return is_numeric($value) ? number_format($value, 2) . ' ' . $currency : '-';
}

function format_number($value) {
	return is_numeric($value) ? number_format($value, 0, ',', '.') : '-';
}

function format_percent($value) {
	return is_numeric($value) ? number_format($value, 2) . ' %' : '-';
}

function format_marketcap($value) {
	if (!is_numeric($value)) return '-';
	if ($value >= 1_000_000_000_000) return round($value / 1_000_000_000_000, 2) . ' Bio $';
	if ($value >= 1_000_000_000) return round($value / 1_000_000_000, 2) . ' Mrd $';
	if ($value >= 1_000_000) return round($value / 1_000_000, 2) . ' Mio $';
	return number_format($value, 0) . ' $';
}
?>

<div class="row">
	<div class="col-12">
		<!-- Firmenkopf -->
		<div class="d-flex align-items-center mb-3">
			<?php
			$imgFallback = '/../../assets/img/company-placeholder.webp';
			$imgSrc = (!empty($profile['image']) && filter_var($profile['image'], FILTER_VALIDATE_URL)) 
				? $profile['image'] 
				: $imgFallback;
			?>
			<img
				src="<?= htmlspecialchars($imgSrc) ?>"
				alt="<?= htmlspecialchars($profile['companyName'] ?? $symbol) ?>"
				loading="lazy"
				decoding="async"
				width="48" height="48"
				class="me-3 rounded-circle border"
				style="object-fit: cover;"
				referrerpolicy="no-referrer"
				onerror="this.onerror=null;this.src='<?= htmlspecialchars($imgFallback) ?>';"
			/>
			<div>
				<h4 class="mb-0"><?= htmlspecialchars($profile['companyName'] ?? '-') ?> <small class="text-muted">(<?= strtoupper($symbol) ?>)</small></h4>
			</div>
		</div>

		<!-- Beschreibung -->
		<div class="card mb-4">
			<div class="card-body">
				<?php if (!empty($profile['description'])): ?>
					<h5 class="mb-2">Beschreibung:</h5>
					<p class="mb-0"><?= nl2br(htmlspecialchars(translate_libre($profile['description'], 'en', 'de'))) ?></p>
				<?php endif; ?>
			</div>
		</div>

		<!-- Unternehmensdetails -->
		<div class="card">
			<div class="card-body">
				<h5 class="mb-3">Unternehmensdetails:</h5>
				<div class="row">
					<div class="col-md-6">
						<p><strong>Aktueller Kurs:</strong> <?= format_currency($profile['price'] ?? null, $profile['currency'] ?? 'USD') ?></p>
						<p><strong>Veränderung (absolut):</strong> <?= format_currency($profile['changes'] ?? null, $profile['currency'] ?? 'USD') ?></p>
						<p><strong>Beta:</strong> <?= $profile['beta'] ?? '-' ?></p>
						<p><strong>Durchschn. Volumen:</strong> <?= format_number($profile['volAvg'] ?? null) ?></p>
						<p><strong>Marktkapitalisierung:</strong> <?= format_marketcap($profile['mktCap'] ?? null) ?></p>
						<p><strong>Letzte Dividende:</strong> <?= format_currency($profile['lastDiv'] ?? null, $profile['currency'] ?? 'USD') ?></p>
						<p><strong>Währung:</strong> <?= htmlspecialchars($profile['currency'] ?? '-') ?></p>
						<p><strong>Kursrange:</strong> <?= htmlspecialchars($profile['range'] ?? '-') ?></p>
					</div>
					<div class="col-md-6">
						<p><strong>Branche:</strong> <?= htmlspecialchars($profile['industry'] ?? '-') ?></p>
						<p><strong>Sektor:</strong> <?= htmlspecialchars($profile['sector'] ?? '-') ?></p>
						<p><strong>Börse:</strong> <?= htmlspecialchars($profile['exchange'] ?? '-') ?></p>
						<p><strong>Börsenkürzel:</strong> <?= htmlspecialchars($profile['exchangeShortName'] ?? '-') ?></p>
						<p><strong>ISIN:</strong> <?= htmlspecialchars($profile['isin'] ?? '-') ?></p>
						<p><strong>CUSIP:</strong> <?= htmlspecialchars($profile['cusip'] ?? '-') ?></p>
						<p><strong>CIK:</strong> <?= htmlspecialchars($profile['cik'] ?? '-') ?></p>
						<p><strong>Website:</strong>
							<?php if (!empty($profile['website'])): ?>
								<a href="<?= htmlspecialchars($profile['website']) ?>" target="_blank" rel="noopener noreferrer"><?= htmlspecialchars($profile['website']) ?></a>
							<?php else: ?>
								-
							<?php endif; ?>
						</p>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<div class="row g-3 mt-3">
	<div class="col-12">
		<h5 class="mb-0">Weiterführende Analysen:</h5>
	</div>
	<div class="col-md-3">
		<div class="card">
			<div class="card-body">
				<i class="fa-solid fa-circle-chevron-right me-1"></i>
				<a href="https://www.google.com/search?q=<?= htmlspecialchars($profile['companyName']) ?>" target="_blank" rel="noopener" class="text-decoration-none text-dark">Bei Google suchen</a>
			</div>
		</div>
	</div>
	<div class="col-md-3">
		<div class="card">
			<div class="card-body">
				<i class="fa-solid fa-circle-chevron-right me-1"></i>
				<a href="#" onclick="copyAndOpenChatGPT('Wie bewertest Du aktuell die Aktie von <?= htmlspecialchars($profile['companyName']) ?> (<?= htmlspecialchars($symbol) ?>)?'); return false;" class="text-decoration-none text-dark">Bei ChatGPT suchen</a>
			</div>
		</div>
	</div>
	<div class="col-md-3">
		<div class="card">
			<div class="card-body">
				<i class="fa-solid fa-circle-chevron-right me-1"></i>
				<a href="/minervini-kriterien.php?symbol=<?= htmlspecialchars($symbol) ?>" target="_blank" rel="noopener" class="text-decoration-none text-dark">Kriterien Mark Minervini</a>
			</div>
		</div>
	</div>
	<div class="col-md-3">
		<div class="card">
			<div class="card-body">
				<i class="fa-solid fa-circle-chevron-right me-1"></i>
				<a href="/saisonalität.php?symbol=<?= htmlspecialchars($symbol) ?>" target="_blank" rel="noopener" class="text-decoration-none text-dark">Saisonalität prüfen</a>
			</div>
		</div>
	</div>
</div>

<script>
function copyAndOpenChatGPT(prompt) {
  navigator.clipboard.writeText(prompt)
	.then(() => {
	  window.open('https://chatgpt.com', '_blank');
	})
	.catch(err => {
	  console.error('Kopieren fehlgeschlagen:', err);
	  window.open('https://chatgpt.com', '_blank');
	});
}
</script>