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

function fetch_recent_insider_trades($limit = 1000) {
	$resp = fmp_multi([
		'insider' => [
			'key'   => 'insider_trading',
			'vars'  => [],
			'query' => [
				'limit' => (int)$limit
			]
		]
	], 4);

	$data = $resp['insider'] ?? [];

	// Falls JSON-String → dekodieren
	if (is_string($data)) {
		$tmp = json_decode($data, true);
		if (json_last_error() === JSON_ERROR_NONE) {
			$data = $tmp;
		}
	}
	if (is_object($data)) {
		$data = json_decode(json_encode($data), true);
	}
	if (isset($data['body'])) $data = $data['body'];
	if (isset($data['data'])) $data = $data['data'];

	return is_array($data) ? $data : [];
}

function classify_trade($trade) {
	$type     = strtolower($trade['transactionType'] ?? '');
	$acq_disp = strtolower($trade['acquistionOrDisposition'] ?? '');
	$shares   = $trade['securitiesTransacted'] ?? 0;
	$price    = $trade['price'] ?? 0;
	$total    = $shares * $price;

	if ($price <= 0 || $shares <= 0) return 'neutral';
	if ($acq_disp === 'a' && $total >= 100000) return 'big_buy';
	if ($acq_disp === 'd' && $total >= 100000) return 'big_sell';
	return 'neutral';
}

$trades = fetch_recent_insider_trades();
?>

<main class="flex-grow-1">
	<section>
		<div class="container my-5">
			<h1 class="mb-4">Insider Trades</h1>

			<?php if (empty($trades)): ?>
				<div class="alert alert-warning">Keine Daten verfügbar.</div>
			<?php else: ?>
				<div class="table-responsive">
					<table class="table">
						<thead class="table-dark">
							<tr>
								<th>Richtung</th>
								<th>Datum</th>
								<th>Symbol</th>
								<th>Name</th>
								<th>Typ</th>
								<th>Stück</th>
								<th>Preis</th>
								<th>Volumen</th>
								<th>SEC</th>
								<th>Analyse</th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ($trades as $t): ?>
								<?php
									$class = classify_trade($t);
									$rowClass = match($class) {
										'big_buy'  => 'table-success',
										'big_sell' => 'table-danger',
										default    => ''
									};
									$total = $t['securitiesTransacted'] * $t['price'];
									$richtung = strtoupper($t['acquistionOrDisposition'] ?? '');
									$badgeClass = match($richtung) {
										'A' => 'success',
										'D' => 'danger',
										default => 'secondary'
									};
									$badgeLabel = match($richtung) {
										'A' => 'Kauf',
										'D' => 'Verkauf',
										default => '–'
									};
								?>
								<tr class="<?= $rowClass ?>">
									<td>
										<span class="badge bg-<?= $badgeClass ?>">
											<?= $badgeLabel ?>
										</span>
									</td>
									<td><?= date('d.m.Y', strtotime($t['transactionDate'])) ?></td>
									<td><strong><?= htmlspecialchars($t['symbol']) ?></strong></td>
									<td><?= htmlspecialchars($t['reportingName']) ?></td>
									<td><?= htmlspecialchars($t['transactionType']) ?></td>
									<td class="text-end"><?= number_format($t['securitiesTransacted']) ?></td>
									<td class="text-end"><?= number_format($t['price'], 2) ?> $</td>
									<td class="text-end"><?= number_format($total, 0) ?> $</td>
									<td class="text-center">
										<a href="<?= htmlspecialchars($t['link']) ?>" target="_blank" rel="noopener" class="text-dark">SEC</a>
									</td>
									<td class="text-center">
										<a href="/aktienbewertung.php?symbol=<?= htmlspecialchars($t['symbol']) ?>" target="_blank" rel="noopener" class="text-dark">Analyse</a>
									</td>
								</tr>
							<?php endforeach; ?>
						</tbody>

					</table>
				</div>
			<?php endif; ?>
		</div>
	</section>
</main>

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