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

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

$data = [];
$entries = $data['raw']['dividends']['historical'] ?? [];
$ratios  = $data['raw']['ratios-ttm'][0] ?? [];
$currentPrice = $data['price'] ?? null;

// --- 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([
	  'dividends'  => ['key' => 'stock_dividend', 'vars' => ['symbol' => $symbol], 'query' => ['limit' => 200]],
	  'ratios_ttm' => ['key' => 'ratios_ttm',     'vars' => ['symbol' => $symbol]],
	  'quote'      => ['key' => 'quote_short',    'vars' => ['symbol' => $symbol]],
	], 12);
	
	$entries = $resp['dividends']['historical'] ?? ($resp['dividends'] ?? []);
	$ratios  = $resp['ratios_ttm'][0] ?? ($resp['ratios_ttm'] ?? []);
	$currentPrice = $resp['quote'][0]['price'] ?? ($resp['quote']['price'] ?? null);
} catch (\Throwable $ex) {
	error_log('[tab_dividends] FMP Fetch Error: ' . $ex->getMessage());
}
// --- End Daten-Wiring ---


$dividendsByYear = [];
$growthByYear = [];
$firstYear = null;
$lastYear = null;
$currentYear = date('Y');
$currentYearDividends = 0;
$currentYearPayments = 0;
$lastDividendAmount = null;
$lastDividendDate = null;

// Dividendenverarbeitung
foreach ($entries as $entry) {
	if (!isset($entry['date'], $entry['dividend'])) continue;

	$year = date('Y', strtotime($entry['date']));
	$dividendsByYear[$year] = ($dividendsByYear[$year] ?? 0) + $entry['dividend'];

	if ($year == $currentYear) {
		$currentYearDividends += $entry['dividend'];
		$currentYearPayments++;
	}

	if (!$lastDividendDate || strtotime($entry['date']) > strtotime($lastDividendDate)) {
		$lastDividendAmount = $entry['dividend'];
		$lastDividendDate   = $entry['date'];
	}
}

ksort($dividendsByYear);
$hasData = count($dividendsByYear) > 0;

// Arrays für Chart
$yearsArray = array_keys($dividendsByYear);
$amountsArray = array_values($dividendsByYear);
$values = $amountsArray;

$totalYears = count($yearsArray);
$firstYear = $yearsArray[0] ?? null;
$lastYear  = $yearsArray[$totalYears - 1] ?? null;

// JSON für Chart.js
$years = json_encode($yearsArray);
$amounts = json_encode($amountsArray);

// Dividendenwachstum pro Jahr
$previous = null;
foreach ($dividendsByYear as $year => $div) {
	$growthByYear[$year] = ($previous !== null && $previous > 0)
		? round((($div - $previous) / $previous) * 100, 2)
		: null;
	$previous = $div;
}

// CAGR
$cagr = null;
if ($totalYears >= 2 && $values[0] > 0) {
	$start = $values[0];
	$end   = $values[$totalYears - 1];
	$periods = $totalYears - 1;
	$cagr = round((pow($end / $start, 1 / $periods) - 1) * 100, 2);
}

// Dividendenrendite
$dividendPerShareTTM = $ratios['dividendPerShareTTM'] ?? null;
$payoutRatio = $ratios['payoutRatioTTM'] ?? null;
$yield = $ratios['dividendYielPercentageTTM']
  ?? $ratios['dividendYieldTTM']
  ?? null;
  
// Wachstumsdaten für Chart.js
$growthYears = json_encode(array_keys($growthByYear));
$growthValues = json_encode(array_map(function($val) {
  return $val !== null ? $val : 'null';
}, array_values($growthByYear)));

$growthSma3 = [];
$growthValuesOnly = array_values($growthByYear);
$growthYearsOnly  = array_keys($growthByYear);

for ($i = 0; $i < count($growthValuesOnly); $i++) {
	$window = array_slice($growthValuesOnly, max(0, $i - 2), 3);
	$valid = array_filter($window, fn($v) => is_numeric($v));
	$growthSma3[$growthYearsOnly[$i]] = count($valid) === 3
		? round(array_sum($valid) / 3, 2)
		: null;
}

$growthYearsJS = json_encode($growthYearsOnly);
$growthValuesJS = json_encode(array_map(fn($v) => $v ?? 'null', $growthValuesOnly));
$growthSma3JS = json_encode(array_map(fn($v) => $v ?? 'null', array_values($growthSma3)));

// Coverage
$dividendCoverage = $ratios['dividendPaidAndCapexCoverageRatioTTM'] ?? null;
$fcfPerShare = $ratios['freeCashFlowPerShareTTM'] ?? null;

// Dividendenqualitätsscore (1–10)
$scoreDividende = 0;
$scoreKriterien = [];

// 1. Dividendenrendite ≥ 3%
if ($yield !== null) {
	if ($yield >= 7)       { $scoreDividende += 2; $scoreKriterien[] = 'Sehr hohe Rendite (≥7%)'; }
	elseif ($yield >= 4.5) { $scoreDividende += 1.5; $scoreKriterien[] = 'Hohe Rendite (≥4.5%)'; }
	elseif ($yield >= 3)   { $scoreDividende += 1; $scoreKriterien[] = 'Solide Rendite (≥3%)'; }
	else                   { $scoreKriterien[] = 'Geringe Rendite (<3%)'; }
}

// 2. Payout Ratio zwischen 30% und 70%
if ($payoutRatio !== null) {
	if ($payoutRatio >= 0.3 && $payoutRatio <= 0.7) {
		$scoreDividende += 2;
		$scoreKriterien[] = 'Nachhaltige Ausschüttungsquote (30–70%)';
	} elseif ($payoutRatio < 0.3) {
		$scoreDividende += 1;
		$scoreKriterien[] = 'Niedrige Ausschüttung (<30%)';
	} else {
		$scoreKriterien[] = 'Hohe Ausschüttung (>70%)';
	}
}

// 3. Dividendenwachstum positiv (CAGR > 0%)
if ($cagr !== null) {
	if ($cagr >= 7)       { $scoreDividende += 2; $scoreKriterien[] = 'Sehr gutes Wachstum (≥7%)'; }
	elseif ($cagr >= 3)   { $scoreDividende += 1.5; $scoreKriterien[] = 'Stabiles Wachstum (≥3%)'; }
	elseif ($cagr > 0)    { $scoreDividende += 1; $scoreKriterien[] = 'Leichtes Wachstum (>0%)'; }
	else                  { $scoreKriterien[] = 'Kein Wachstum'; }
}

// 4. Letzte Zahlung vor ≤ 365 Tagen
if ($lastDividendDate) {
	$daysSinceLast = (new DateTime())->diff(new DateTime($lastDividendDate))->days;
	if ($daysSinceLast <= 365) {
		$scoreDividende += 1;
		$scoreKriterien[] = 'Letzte Zahlung <1 Jahr her';
	} else {
		$scoreKriterien[] = 'Zahlung >1 Jahr zurück';
	}
}

// 5. CapEx-Deckung ≥ 1.2
if ($dividendCoverage !== null) {
	if ($dividendCoverage >= 1.5)      { $scoreDividende += 2; $scoreKriterien[] = 'Sehr gute Deckung (≥1.5)'; }
	elseif ($dividendCoverage >= 1.2)  { $scoreDividende += 1; $scoreKriterien[] = 'Solide Deckung (≥1.2)'; }
	else                               { $scoreKriterien[] = 'Schwache Deckung (<1.2)'; }
}

// Farben-Logik je nach Score
$scoreDivColor =
	$scoreDividende >= 8 ? 'success' :
	($scoreDividende >= 5 ? 'warning' : 'danger');

// Tooltip-Text erzeugen
$scoreTooltip = htmlspecialchars(implode(" • ", $scoreKriterien));

// Score auf 1–10 normieren
$scoreDividende = min(10, round($scoreDividende, 1));

?>

<?php if ($hasData): ?>
	<div class="row mb-3 g-3">
		<div class="col-md-3">
			<div class="card">
				<div class="card-body">
					<p class="mb-0">Letzte Dividende:</p>
					<?php if ($lastDividendAmount && $lastDividendDate): ?>
						<h3><strong><?= number_format($lastDividendAmount, 2) ?> $</strong></h3>
						<small>Ex-Datum: <?= date('d.m.Y', strtotime($lastDividendDate)) ?></small>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<div class="col-md-3">
			<div class="card">
				<div class="card-body">
					<p class="mb-0">Aktuelle Summe:</p>
					<?php if ($currentYearDividends && $currentYearPayments): ?>
						<h3><strong><?= number_format($currentYearDividends, 2) ?> $</strong></h3>
						<small><?= $currentYear ?>:  (<?= $currentYearPayments ?> Zahlungen)</small>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<div class="col-md-3">
			<div class="card">
				<div class="card-body">
					<p class="mb-0">Dividendenrendite (TTM):</p>
					<?php if ($yield !== null): ?>
						<h3><strong><?= round($yield, 2) ?>%</strong></h3>
						<small>Payout Ratio: <strong><?= round($payoutRatio * 100, 1) ?>%</strong></small>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<div class="col-md-3">
			<div class="card">
				<div class="card-body">
					<p class="mb-0">Dividenden + CapEx Coverage:</p>
					<?php if ($dividendCoverage !== null): ?>
						<h3><strong><?= round($dividendCoverage, 2) ?></strong></h3>
					<?php endif; ?>
					<?php if ($fcfPerShare !== null): ?>
						<small>Free Cashflow pro Aktie (TTM): <strong><?= round($fcfPerShare, 2) ?> $</strong></small>
					<?php endif; ?>
				</div>
			</div>
		</div>
	</div>
	<div class="row">
		<div class="col-12">
			<div class="alert alert-<?= $scoreDivColor ?>">
				<h6 class="mb-0">
					Dividendenqualität:
					<strong><?= $scoreDividende ?>/10</strong>
				</h6>
				<small><?= $scoreTooltip ?></small>
			</div>
		</div>
	</div>

	<!-- Chart -->
	<div class="row">
		<div class="col-12">
			<div class="card">
				<div class="card-body">
					<h5 class="card-title">Dividendenhistorie (jährlich) (<?= htmlspecialchars($symbol) ?>)</h5>
					<canvas id="dividendenChart" height="80"></canvas>
				</div>
			</div>
		</div>
	</div>

	<!-- Wachstum -->
	<div class="row mt-3">
		<div class="col-12">
			<div class="card">
				<div class="card-body">
					<h5 class="card-title">Dividendenwachstum pro Jahr (<?= htmlspecialchars($symbol) ?>)</h5>
					<?php if ($cagr !== null): ?>
						<small>Ø Wachstum p.a. (CAGR): <strong><?= $cagr ?>%</strong></small>
					<?php endif; ?>
					<?php if ($firstYear === $lastYear): ?>
						(<small>Daten für Jahr: <strong><?= $firstYear ?></strong></small>)
					<?php else: ?>
						(<small>Daten von <strong><?= $firstYear ?></strong> bis <strong><?= $lastYear ?></strong></small>)
					<?php endif; ?>
					<canvas id="dividendenGrowthChart" height="80"></canvas>
				</div>
			</div>
		</div>
	</div>

<?php elseif ($symbol): ?>
	<!-- Kein Ergebnis -->
	<div class="row mt-3">
		<div class="col-12">
			<div class="alert alert-warning text-center">
				Das Unternehmen <strong><?= htmlspecialchars($symbol) ?></strong> hat keine Dividendenhistorie.
			</div>
		</div>
	</div>
<?php endif; ?>

<?php if ($hasData): ?>
<script>
function renderDividendenChart() {
	const canvas = document.getElementById('dividendenChart');
	if (!canvas) return console.warn("Canvas fehlt");

	const ctx = canvas.getContext('2d');
	new Chart(ctx, {
		type: 'bar',
		data: {
			labels: <?= $years ?>,
			datasets: [{
				label: 'Dividende pro Jahr (USD)',
				data: <?= $amounts ?>,
				backgroundColor: 'rgba(0, 0, 0, 0.85)'
			}]
		},
		options: {
			responsive: true,
			scales: {
				y: {
					beginAtZero: true,
					ticks: {
						stepSize: 0.5,
						callback: function(value) {
							return '$' + value.toFixed(2);
						}
					},
					title: {
						display: true,
						text: 'Summe pro Jahr in USD'
					}
				},
				x: {
					title: {
						display: true,
						text: 'Jahr'
					}
				}
			},
			plugins: {
				legend: { display: false },
				tooltip: {
					callbacks: {
						label: (ctx) => `Dividende: $${ctx.parsed.y.toFixed(2)}`
					}
				}
			}
		}
	});
}

if (typeof Chart !== 'undefined') {
	renderDividendenChart();
}
</script>

<script>
function renderDividendenGrowthChart() {
	const canvas = document.getElementById('dividendenGrowthChart');
	if (!canvas) return;

	const ctx = canvas.getContext('2d');
	new Chart(ctx, {
		type: 'bar',
		data: {
			labels: <?= $growthYearsJS ?>,
			datasets: [
				{
					type: 'bar',
					label: 'Wachstum (%)',
					data: <?= $growthValuesJS ?>,
					backgroundColor: 'rgba(0, 0, 0, 1)'
				},
				{
					type: 'line',
					label: 'Ø 3 Jahre',
					data: <?= $growthSma3JS ?>,
					borderColor: 'rgba(255, 0, 0, 1)',
					backgroundColor: 'rgba(255, 0, 0, 0.1)',
					borderWidth: 1,
					tension: 0.2,
					pointRadius: 0,
					fill: false
				}
			]
		},
		options: {
			responsive: true,
			scales: {
				y: {
					beginAtZero: false,
					ticks: {
						callback: function(value) {
							return value + '%';
						}
					},
					title: {
						display: true,
						text: 'Wachstumsrate (%)'
					}
				},
				x: {
					title: {
						display: true,
						text: 'Jahr'
					}
				}
			},
			plugins: {
				tooltip: {
					mode: 'index',
					intersect: false,
					callbacks: {
						label: function(ctx) {
							let v = ctx.parsed.y;
							return `${ctx.dataset.label}: ${isNaN(v) ? '–' : v.toFixed(2) + '%'}`;
						}
					}
				}
			}
		}
	});
}

if (typeof Chart !== 'undefined') {
	renderDividendenGrowthChart();
}
</script>

<?php endif; ?>