<?php
// Tab: Minervini – Darstellung 1:1 wie in der Vorlage (Score-Banner + Balken + zwei Tabellen).
// Berechnung bleibt extern.

$symbol = $GLOBALS['tab_symbol'] ?? '';
$asof   = $GLOBALS['tab_asof'] ?? null;

require_once __DIR__ . '/../../engine/bewertungsmethoden/bewertung_minervini.php';
require_once __DIR__ . '/../../engine/api-handling/fmp_client.php'; // nur für Firmenbild/Name

$result = null;
if (!empty($symbol) && function_exists('calculate_minervini_score')) {
	try {
		$result = calculate_minervini_score($symbol);
	} catch (Throwable $ex) {
		error_log('[tab_minervini] Error: ' . $ex->getMessage());
	}
}

$hasData = is_array($result) && !empty($result);
$technicalCriteria   = $hasData ? ($result['technicalCriteria']   ?? []) : [];
$fundamentalCriteria = $hasData ? ($result['fundamentalCriteria'] ?? []) : [];
$technicalScore      = $hasData ? (int)($result['technicalScore']      ?? 0)  : 0;
$fundamentalScore    = $hasData ? (int)($result['fundamentalScore']    ?? 0)  : 0;
$maxScore            = $hasData ? (int)($result['maxScore']            ?? ($technicalScore+$fundamentalScore)) : 0;
$totalScore          = $hasData ? (int)($result['score']               ?? ($technicalScore + $fundamentalScore)) : 0;
$resultMessage       = $hasData ? ($result['resultMessage']       ?? '') : '';

$companyImg = '';
$companyName = strtoupper($symbol);

// Nur für das Badge-Bild/Name: leichtgewichtiger Profile-Call
try {
	if (!empty($symbol) && function_exists('fmp_multi')) {
		$resp = fmp_multi([
			'profile' => ['key' => 'profile', 'vars' => ['symbol' => $symbol]],
		], 6);
		$prof = $resp['profile'] ?? [];
		if (isset($prof[0]) && is_array($prof[0])) $prof = $prof[0];
		if (is_array($prof)) {
			$companyImg = $prof['image'] ?? ($prof['profileImage'] ?? '');
			$companyName = $prof['companyName'] ?? $companyName;
		}
	}
} catch (Throwable $e) {
	// optional
}

$percent = ($maxScore > 0) ? round(($totalScore / $maxScore) * 100, 1) : 0;

// Annahme: max technisch = Anzahl technischer Kriterien, max fundamental = Anzahl fundamentaler Kriterien
$maxTech = max(count($technicalCriteria), ($technicalScore ?: 0));
$maxFund = max(count($fundamentalCriteria), ($fundamentalScore ?: 0));
	
if (!function_exists('ampel_class_by_percent')) {
	function ampel_class_by_percent(float $p): string {
		if ($p >= 75) return 'success';   // grün
		if ($p >= 55) return 'warning';   // gelb
		return 'danger';                  // rot
	}
}
if (!function_exists('ampel_text_by_percent')) {
	function ampel_text_by_percent(float $p): string {
		if ($p >= 75) return 'Grün – stark';
		if ($p >= 55) return 'Gelb – neutral';
		return 'Rot – schwach';
	}
}
?>
<?php if ($hasData): ?>
<div class="row">
	<div class="col-md-6">
		<?php
			$percent    = ($maxScore > 0) ? round(100 * $totalScore / $maxScore, 1) : 0.0;
			$ampelClass = ampel_class_by_percent($percent);
			$ampelText  = ampel_text_by_percent($percent);
		?>
		<div class="alert alert-<?= htmlspecialchars($ampelClass) ?> d-flex justify-content-start align-items-center">
			<?php
			$imgFallback = '/../../assets/img/company-placeholder.webp';
			$imgSrc = (!empty($companyImg) && filter_var($companyImg, FILTER_VALIDATE_URL)) 
				? $companyImg 
				: $imgFallback;
			?>
			<img
				src="<?= htmlspecialchars($imgSrc) ?>"
				alt="<?= htmlspecialchars($companyName) ?>"
				loading="lazy"
				decoding="async"
				width="60" height="60"
				class="rounded-circle border me-3"
				style="object-fit:cover;"
				referrerpolicy="no-referrer"
				onerror="this.onerror=null;this.src='<?= htmlspecialchars($imgFallback) ?>';"
			/>
			<div>
				<h5 class="fw-bold">
					<?= (int)$totalScore ?> / <?= (int)$maxScore ?> Punkte (<?= number_format($percent, 1) ?> %)
				</h5>
				<?php if (!empty($resultMessage)): ?>
					<?= htmlspecialchars($resultMessage) ?>
				<?php endif; ?>
			</div>
		</div>
	</div>
	<div class="col-md-6">
			<div class="d-flex justify-content-between fw-bold">
				<small>Technik</small><small><?= (int)$technicalScore ?>/<?= (int)$maxTech ?></small>
			</div>
			<div class="progress" style="height:10px;" role="progressbar" aria-label="Technik" aria-valuenow="<?= (int)$technicalScore ?>" aria-valuemin="0" aria-valuemax="<?= (int)$maxTech ?>">
				<div class="progress-bar bg-black" style="width: <?= ($maxTech>0? ($technicalScore/$maxTech*100) : 0) ?>%"></div>
			</div>
			<div class="d-flex justify-content-between fw-bold mt-3"">
				<small>Fundamental</small><small><?= (int)$fundamentalScore ?>/<?= (int)$maxFund ?></small>
			</div>
			<div class="progress" style="height:10px;" role="progressbar" aria-label="Fundamental" aria-valuenow="<?= (int)$fundamentalScore ?>" aria-valuemin="0" aria-valuemax="<?= (int)$maxFund ?>">
				<div class="progress-bar bg-black" style="width: <?= ($maxFund>0? ($fundamentalScore/$maxFund*100) : 0) ?>%"></div>
			</div>
	</div>
</div>

<div class="row mt-3">
	<div class="col-md-6">
		<h5 class="mb-3">Technische Kriterien</h5>
		<div class="table-responsive">
			<table class="table align-middle">
				<thead class="table-dark">
					<tr>
						<th></th>
						<th>Kriterium</th>
						<th class="text-end">Wert (Basis)</th>
					</tr>
				</thead>
				<tbody>
				<?php foreach ($technicalCriteria as $krit): ?>
					<tr>
						<td>
							<?php if (!empty($krit['erfüllt'])): ?>
								<i class="fas fa-check text-success" aria-hidden="true"></i> <span class="visually-hidden">Erfüllt</span>
							<?php else: ?>
								<i class="fas fa-xmark text-danger" aria-hidden="true"></i> <span class="visually-hidden">Nicht erfüllt</span>
							<?php endif; ?>
						</td>
						<td>
							<?= htmlspecialchars($krit['Kriterium'] ?? '') ?>
						</td>
						<td class="text-end"><?= htmlspecialchars($krit['wert'] ?? '') ?></td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
	</div>

	<div class="col-md-6">
		<h5 class="mb-3">Fundamentale Kriterien</h5>
		<div class="table-responsive">
			<table class="table align-middle">
				<thead class="table-dark">
					<tr>
						<th></th>
						<th>Kriterium</th>
						<th class="text-end">Wert (Basis)</th>
					</tr>
				</thead>
				<tbody>
				<?php foreach ($fundamentalCriteria as $krit): ?>
					<tr>
						<td>
							<?php if (!empty($krit['erfüllt'])): ?>
								<i class="fas fa-check text-success" aria-hidden="true"></i> <span class="visually-hidden">Erfüllt</span>
							<?php else: ?>
								<i class="fas fa-xmark text-danger" aria-hidden="true"></i> <span class="visually-hidden">Nicht erfüllt</span>
							<?php endif; ?>
						</td>
						<td>
							<?= htmlspecialchars($krit['Kriterium'] ?? '') ?>
						</td>
						<td class="text-end"><?= htmlspecialchars($krit['wert'] ?? '') ?></td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
	</div>
</div>
<?php elseif (!empty($symbol)): ?>
<div class="alert alert-warning text-center mt-3">
	Keine Daten für <strong><?= htmlspecialchars(strtoupper($symbol)) ?></strong> verfügbar.
</div>
<?php endif; ?>
