<?php

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

/**
 * Minervini-Score berechnen (technisch + fundamental).
 *
 * @param string $symbol
 * @return array
 */
function calculate_minervini_score(string $symbol): array
{
	$technicalScore         = 0;
	$fundamentalScore       = 0;
	$maxScore               = 14;
	$technischeKriterien    = [];
	$fundamentaleKriterien  = [];
	$resultMessage          = '';

	if ($symbol) {

		// Alle nötigen Daten per Multi-Request laden
		$res = fmp_multi([
			'profile' => [
				'key'  => 'profile',
				'vars' => ['symbol' => $symbol]
			],
			'income' => [
				'key'   => 'income_statement',
				'vars'  => ['symbol' => $symbol],
				'query' => ['limit' => 4]
			],
			'metrics' => [
				'key'  => 'key_metrics_ttm',
				'vars' => ['symbol' => $symbol]
			],
			'prices' => [
				'key'   => 'historical_price_full',
				'vars'  => ['symbol' => $symbol],
				'query' => [
					'from'       => date('Y-m-d', strtotime('-450 days')),
					'serietype'  => 'line'
				]
			]
		]);

		$profile = is_array($res['profile']) ? ($res['profile'][0] ?? []) : [];
		$income  = $res['income'] ?? [];
		$metrics = is_array($res['metrics']) ? ($res['metrics'][0] ?? []) : [];
		$prices  = isset($res['prices']['historical']) ? $res['prices']['historical'] : [];

		// Preise chronologisch (alt → neu)
		$rowsChrono = array_reverse($prices);
		$closes     = array_column($rowsChrono, 'close');

		if (!empty($closes)) {
			$price = end($closes);

			// Hilfsfunktion SMA
			$sma = function (array $arr, int $n): ?float {
				$len = count($arr);
				if ($len < $n) return null;
				return array_sum(array_slice($arr, -$n)) / $n;
			};

			$sma50  = $sma($closes, 50);
			$sma150 = $sma($closes, 150);
			$sma200 = $sma($closes, 200);

			$hiLoWindow = min(252, count($closes));
			$high52     = max(array_slice($closes, -$hiLoWindow));
			$low52      = min(array_slice($closes, -$hiLoWindow));

			$relStrength = (count($closes) > 126 && $closes[count($closes) - 127] > 0)
				? (($price / $closes[count($closes) - 127]) - 1) * 100
				: null;

			// Technische Kriterien
			$technischeKriterien[] = [
				'Kriterium' => 'Kurs liegt über dem 50-Tage-Schnitt',
				'erfüllt'   => ($sma50 !== null) ? ($price > $sma50) : false,
				'wert'      => ($sma50 !== null) ? number_format($price, 2) . ' / ' . number_format($sma50, 2) : '–'
			];
			$technischeKriterien[] = [
				'Kriterium' => 'SMA 50 liegt über SMA 150',
				'erfüllt'   => ($sma50 !== null && $sma150 !== null) ? ($sma50 > $sma150) : false,
				'wert'      => ($sma50 !== null && $sma150 !== null) ? number_format($sma50, 2) . ' / ' . number_format($sma150, 2) : '–'
			];
			$technischeKriterien[] = [
				'Kriterium' => 'SMA 150 liegt über SMA 200',
				'erfüllt'   => ($sma150 !== null && $sma200 !== null) ? ($sma150 > $sma200) : false,
				'wert'      => ($sma150 !== null && $sma200 !== null) ? number_format($sma150, 2) . ' / ' . number_format($sma200, 2) : '–'
			];
			$technischeKriterien[] = [
				'Kriterium' => 'Kurs liegt über dem 150-Tage-Schnitt',
				'erfüllt'   => ($sma150 !== null) ? ($price > $sma150) : false,
				'wert'      => ($sma150 !== null) ? number_format($price, 2) . ' / ' . number_format($sma150, 2) : '–'
			];
			$technischeKriterien[] = [
				'Kriterium' => 'Kurs liegt mind. 30% über 52W-Tief und max. 15% unter 52W-Hoch',
				'erfüllt'   => ($low52 > 0) ? ($price >= $low52 * 1.3 && $price >= $high52 * 0.85) : false,
				'wert'      => number_format($price, 2) . ' | Tief: ' . number_format($low52, 2) . ' / Hoch: ' . number_format($high52, 2)
			];
			$technischeKriterien[] = [
				'Kriterium' => 'Relative Stärke (6M) > 15%',
				'erfüllt'   => is_numeric($relStrength) ? ($relStrength > 15) : false,
				'wert'      => is_numeric($relStrength) ? number_format($relStrength, 2) . '%' : '–'
			];

			foreach ($technischeKriterien as $kriterium) {
				if (!empty($kriterium['erfüllt'])) $technicalScore++;
			}

			// Fundamentale Kriterien
			$eps = $income[0]['eps'] ?? null;
			if ($eps === null && isset($income[0]['netIncome'], $income[0]['weightedAverageShsOut'])) {
				$den = (float)$income[0]['weightedAverageShsOut'];
				$eps = $den > 0 ? ((float)$income[0]['netIncome'] / $den) : null;
			}

			$fundamentaleKriterien[] = [
				'Kriterium' => 'EPS ist positiv',
				'erfüllt'   => is_numeric($eps) ? ($eps > 0) : false,
				'wert'      => is_numeric($eps) ? number_format($eps, 2) : '–'
			];

			$pe = (is_numeric($eps) && $eps > 0 && isset($profile['price']))
				? ((float)$profile['price'] / (float)$eps)
				: null;
			$fundamentaleKriterien[] = [
				'Kriterium' => 'KGV liegt im Zielbereich (0–50)',
				'erfüllt'   => is_numeric($pe) ? ($pe > 0 && $pe < 50) : false,
				'wert'      => is_numeric($pe) ? number_format($pe, 2) : '–'
			];

			$peg = null;
			if (isset($income[1]['eps'], $income[0]['eps']) && is_numeric($pe) && $pe > 0) {
				$epsPrev = (float)$income[1]['eps'];
				$epsCurr = (float)$income[0]['eps'];
				if ($epsPrev > 0 && $epsCurr > 0) {
					$growthPct = (($epsCurr / $epsPrev) - 1) * 100;
					if ($growthPct > 0) $peg = $pe / $growthPct;
				}
			}
			$fundamentaleKriterien[] = [
				'Kriterium' => 'PEG-Ratio im Idealbereich (0–1.5)',
				'erfüllt'   => is_numeric($peg) ? ($peg > 0 && $peg < 1.5) : false,
				'wert'      => is_numeric($peg) ? number_format($peg, 2) : '–'
			];

			$marketCap = $profile['mktCap'] ?? ($profile['marketCap'] ?? 0);
			$fundamentaleKriterien[] = [
				'Kriterium' => 'Marktkapitalisierung > 1 Mrd. USD',
				'erfüllt'   => $marketCap > 1_000_000_000,
				'wert'      => is_numeric($marketCap) ? number_format($marketCap, 0, ',', '.') . ' USD' : '–'
			];

			$revenueGrowth = (count($income) >= 4 && isset($income[3]['revenue'], $income[0]['revenue']) && $income[3]['revenue'] > 0)
				? ((($income[0]['revenue'] / $income[3]['revenue']) - 1) * 100)
				: null;
			$fundamentaleKriterien[] = [
				'Kriterium' => 'Umsatzwachstum (3J) > 20%',
				'erfüllt'   => is_numeric($revenueGrowth) ? ($revenueGrowth > 20) : false,
				'wert'      => is_numeric($revenueGrowth) ? number_format($revenueGrowth, 2) . '%' : '–'
			];

			$epsGrowth = (count($income) >= 4 && isset($income[3]['eps'], $income[0]['eps']) && $income[3]['eps'] > 0)
				? ((($income[0]['eps'] / $income[3]['eps']) - 1) * 100)
				: null;
			$fundamentaleKriterien[] = [
				'Kriterium' => 'EPS-Wachstum (3J) > 25%',
				'erfüllt'   => is_numeric($epsGrowth) ? ($epsGrowth > 25) : false,
				'wert'      => is_numeric($epsGrowth) ? number_format($epsGrowth, 2) . '%' : '–'
			];

			$roe = $metrics['roeTTM'] ?? $metrics['roe'] ?? null;
			$fundamentaleKriterien[] = [
				'Kriterium' => 'ROE > 17%',
				'erfüllt'   => is_numeric($roe) ? ($roe > 17) : false,
				'wert'      => is_numeric($roe) ? number_format($roe, 2) . '%' : '–'
			];

			$de = null;
			foreach (['debtToEquity', 'debtToEquityTTM', 'debtEquityTTM', 'debtToEquityRatioTTM', 'debtToEquityRatio'] as $k) {
				if (isset($metrics[$k]) && is_numeric($metrics[$k])) {
					$de = (float)$metrics[$k];
					break;
				}
			}
			$fundamentaleKriterien[] = [
				'Kriterium' => 'Debt/Equity < 0.5',
				'erfüllt'   => is_numeric($de) ? ($de < 0.5) : false,
				'wert'      => is_numeric($de) ? number_format($de, 2) : '–'
			];

			foreach ($fundamentaleKriterien as $kriterium) {
				if (!empty($kriterium['erfüllt'])) $fundamentalScore++;
			}

			$score = $technicalScore + $fundamentalScore;
			$resultMessage = ($score === $maxScore)
				? "$symbol erfüllt alle erweiterten Minervini-Kriterien"
				: "$symbol erfüllt nicht alle Kriterien";
		}
	}

	return [
		'score'                => $technicalScore + $fundamentalScore,
		'technicalScore'       => $technicalScore,
		'fundamentalScore'     => $fundamentalScore,
		'maxScore'             => $maxScore,
		'technicalCriteria'    => $technischeKriterien,
		'fundamentalCriteria'  => $fundamentaleKriterien,
		'resultMessage'        => $resultMessage,
		'name'                 => $profile['companyName']       ?? $symbol,
		'exchange'             => $profile['exchangeShortName'] ?? ($profile['exchange'] ?? ''),
	];
}