<?php
$symbol     = $GLOBALS['tab_symbol'] ?? '';

require_once __DIR__ . '/../../engine/api-handling/fmp_client.php';
$data = [];
$insider_trades = [];
// --- 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.');
	}

	// Insider-Trades: v4 Endpoint, Symbol über Query
	$resp = fmp_multi([
		'insider' => ['key' => 'insider_trading', 'vars' => [], 'query' => ['symbol' => $symbol, 'limit' => 200]],
	], 12);

	$insider_trades = $resp['insider'] ?? [];
	
	if (empty($insider_trades)) {
		?>
		<div class="row mt-3">
			<div class="col-12">
				<div class="alert alert-warning text-center">
					Für <strong><?= htmlspecialchars($symbol) ?></strong> liegen keine Insider-Transaktionen vor.
				</div>
			</div>
		</div>
		<?php
		return;
	}

	// Feld-Mapping für Legacy-Template: acquisitionOrDisposition -> acquisitonOrDisposition (Schreibweise im Tab)
	if (is_array($insider_trades)) {
		foreach ($insider_trades as &$t) {
			if (isset($t['acquisitionOrDisposition']) && !isset($t['acquistionOrDisposition'])) {
				$t['acquistionOrDisposition'] = $t['acquisitionOrDisposition'];
			}
		}
		unset($t);
	}
} catch (\Throwable $ex) {
	error_log('[tab_insider] FMP Fetch Error: ' . $ex->getMessage());
}
// --- End Daten-Wiring ---


if ($symbol) {
	$buyCount = $sellCount = 0;
	$buyTotal = $sellTotal = 0.0;
	
	if (is_array($insider_trades)) {
		foreach ($insider_trades as $t) {
			$dir    = strtoupper($t['acquistionOrDisposition'] ?? $t['acquisitionOrDisposition'] ?? '');
			$shares = $t['securitiesTransacted'] ?? null;
			$price  = $t['price'] ?? null;
			$total  = (is_numeric($shares) && is_numeric($price)) ? ($shares * $price) : null;
	
			if ($dir === 'A') { // Kauf
				$buyCount++;
				if (is_numeric($total)) $buyTotal += $total;
			} elseif ($dir === 'D') { // Verkauf
				$sellCount++;
				if (is_numeric($total)) $sellTotal += $total;
			}
		}
	}
	
	$netTotal = $buyTotal - $sellTotal;
	
	$dates = array_column($insider_trades, 'transactionDate');
	$dates = array_filter($dates); // leere Werte raus
	$earliestDate = !empty($dates) ? min($dates) : null;
	
	if ($earliestDate) {
		$earliestDateFormatted = date('d.m.Y', strtotime($earliestDate));
	} else {
		$earliestDateFormatted = null;
	}
}
?>

<?php if (!empty($insider_trades)): ?>
<div class="row mt-2">
	<div class="col-md-4">
		<div class="card">
			<div class="card-body">
				<div>
					<div class="small">
						Käufe (<?= (int)$buyCount ?>)
					</div>
					<div class="h5 mb-0">
						<strong><?= number_format((float)$buyTotal, 0, ',', '.') ?> USD</strong>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="col-md-4">
		<div class="card">
			<div class="card-body">
				<div>
					<div class="small">
						Verkäufe (<?= (int)$sellCount ?>)
					</div>
					<div class="h5 mb-0">
						<strong><?= number_format((float)$sellTotal, 0, ',', '.') ?> USD</strong>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="col-md-4">
		<?php $netPositive = $netTotal >= 0; ?>
		<div class="card border-<?= $netPositive ? 'success' : 'danger' ?>">
			<div class="card-body d-flex justify-content-between align-items-center">
				<div>
					<div class="small <?= $netPositive ? 'text-success' : 'text-danger' ?>">
						Netto-Saldo<?php if ($earliestDateFormatted): ?> (seit <?= $earliestDateFormatted ?>)<?php endif; ?>
					</div>
					<div class="h5 mb-0">
						<strong><?= number_format((float)$netTotal, 0, ',', '.') ?> USD</strong>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
<div class="row mt-4">
	<div class="col-12">
		<div class="card">
			<div class="card-body">
				<h5 class="mb-1">Letzte Insider-Transaktionen</h5>
				<?php if ($earliestDateFormatted): ?><small>seit <?= $earliestDateFormatted ?></small><?php endif; ?>
				<div class="table-responsive mt-3">
					<table class="table table-sm align-middle mb-0">
						<thead class="table-dark">
							<tr>
								<th>Datum</th>
								<th>Name</th>
								<th>Richtung</th>
								<th>Stück</th>
								<th>Preis</th>
								<th>Volumen</th>
							</tr>
						</thead>
						<tbody>
						<?php foreach ($insider_trades as $trade): ?>
							<?php
								$richtung = strtoupper($trade['acquistionOrDisposition'] ?? '');
								$badge = match ($richtung) {
									'A' => '<span class="badge bg-success">Kauf</span>',
									'D' => '<span class="badge bg-danger">Verkauf</span>',
									default => '<span class="badge bg-secondary">–</span>',
								};
		
								$shares = $trade['securitiesTransacted'] ?? null;
								$price  = $trade['price'] ?? null;
								$total = (is_numeric($shares) && is_numeric($price)) ? $shares * $price : null;
		
								$rowClass = '';
								if ($total >= 100000) {
									if ($richtung === 'A') $rowClass = 'table-success';
									elseif ($richtung === 'D') $rowClass = 'table-danger';
								}
							?>
							<tr class="<?= $rowClass ?>">
								<td><?= date('d.m.Y', strtotime($trade['transactionDate'])) ?></td>
								<td><?= htmlspecialchars($trade['reportingName']) ?></td>
								<td><?= $badge ?>
									<small class="text-muted ms-1"><?= htmlspecialchars($trade['transactionType']) ?></small>
								</td>
								<td class="text-end">
									<?= is_numeric($shares) ? number_format($shares) : '–' ?>
								</td>
								<td class="text-end">
									<?= is_numeric($price) ? number_format($price, 2) . ' $' : '–' ?>
								</td>
								<td class="text-end">
									<?= is_numeric($total) ? number_format($total, 0) . ' $' : '–' ?>
								</td>
							</tr>
						<?php endforeach; ?>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</div>
<?php endif; ?>