<?php
$symbol = isset($_GET['symbol']) ? (string)$_GET['symbol'] : (isset($_REQUEST['symbol']) ? (string)$_REQUEST['symbol'] : '');
$asof   = isset($_GET['asof'])   ? (string)$_GET['asof']   : '';
$group  = isset($_GET['group'])  ? (string)$_GET['group']  : 'analyst';

if ($symbol === '') {
	echo '<div class="alert alert-warning mb-0">Kein Symbol übergeben.</div>';
	return;
}

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

// Feature-Flags: nur aktivieren, wenn die Keys in FMP_ENDPOINTS existieren
$HAS_ESTIMATES = false;   // erst auf true setzen, wenn 'analyst_estimates' in fmp_registry drin ist
$HAS_EARNINGS  = false;   // erst auf true setzen, wenn 'earnings_company'   in fmp_registry drin ist

$req = [
  'recs'   => ['key'=>'analyst_recommendations','vars'=>['symbol'=>$symbol]],
  'pt'     => ['key'=>'price_target','vars'=>['symbol'=>$symbol]],
  'pt_sum' => ['key'=>'price_target_summary','vars'=>['symbol'=>$symbol]],
];

if ($HAS_ESTIMATES) {
  $req['est'] = ['key'=>'analyst_estimates','vars'=>[], 'query'=>[
	'symbol'=>$symbol, 'period'=>'annual', 'limit'=>12, 'page'=>0
  ]];
}
if ($HAS_EARNINGS) {
  $req['earn'] = ['key'=>'earnings_company','vars'=>[], 'query'=>['symbol'=>$symbol]];
}

// Sicherer Multi-Fetch
try {
  $multi = fmp_multi([
	'recs'   => ['key'=>'analyst_recommendations','vars'=>['symbol'=>$symbol]],
	'pt'     => ['key'=>'price_target','vars'=>['symbol'=>$symbol]],
	'pt_sum' => ['key'=>'price_target_summary','vars'=>['symbol'=>$symbol]],
	'rating' => [
	  'key'   => 'rating',
	  'vars'  => ['symbol' => $symbol],
	  'query' => ['limit' => 1],
	],
	
	'hist_rating' => [
	  'key'   => 'historical_rating',
	  'vars'  => ['symbol' => $symbol],
	  'query' => ['limit' => 400],
	]
  ]);
} catch (Throwable $e) {
  $multi = [];
}

// Robust auspacken
$recsArr  = $multi['recs']   ?? [];
$ptArr    = $multi['pt']     ?? [];
$ptSumArr = $multi['pt_sum'] ?? [];
$estArr   = $multi['est']    ?? [];
$earnArr  = $multi['earn']   ?? [];
$histRatingArr = $multi['hist_rating'] ?? [];

// Aktuelles Rating für die Karte
$ratingArr  = $multi['rating'] ?? [];
$rating     = (is_array($ratingArr) && isset($ratingArr[0])) ? $ratingArr[0] : (is_array($ratingArr) ? $ratingArr : []);

// Historie primär aus /historical-rating
$histList = (is_array($histRatingArr) && isset($histRatingArr[0]) && is_array($histRatingArr[0]))
  ? $histRatingArr
  : ((is_array($histRatingArr) && $histRatingArr) ? [$histRatingArr] : []);

// Fallback: falls historical_rating leer ist, versuche /rating (falls mehrere Zeilen)
if (!$histList) {
  $ratingArrAll = $multi['rating'] ?? [];
  if (is_array($ratingArrAll) && isset($ratingArrAll[0]) && is_array($ratingArrAll[0]) && count($ratingArrAll) > 1) {
	$histList = $ratingArrAll;
  }
}

// Datum aus 'date' ODER 'ratingDate'
$extractDate = function(array $row) {
  return $row['date'] ?? ($row['ratingDate'] ?? null);
};

// Historie chronologisch (alt → neu) sortieren
if ($histList) {
  usort($histList, function($a,$b) use ($extractDate){
	$da = $extractDate($a) ? strtotime($extractDate($a)) : 0;
	$db = $extractDate($b) ? strtotime($extractDate($b)) : 0;
	return $da <=> $db;
  });
}

// ===== Resampler: quarterly | monthly =====
if (!function_exists('resample_ratings')) {
  function resample_ratings(array $histList, string $period = 'quarterly'): array {
	$bucket = []; // key => ['date'=>..., 'row'=>...]
	foreach ($histList as $row) {
	  $d = $row['date'] ?? ($row['ratingDate'] ?? null);
	  if (!$d) continue;
	  $ts = strtotime($d);
	  if ($period === 'quarterly') {
		$q  = (int)ceil((int)date('n',$ts)/3);
		$k  = date('Y',$ts)."-Q{$q}";
	  } else {
		$k  = date('Y-m',$ts); // monthly
	  }
	  // pro Periode den letzten Eintrag behalten
	  if (!isset($bucket[$k]) || strtotime($bucket[$k]['date']) < $ts) {
		$bucket[$k] = ['date'=>date('Y-m-d',$ts), 'row'=>$row];
	  }
	}
	// nach Datum sortieren, alt->neu
	uasort($bucket, fn($a,$b)=>strcmp($a['date'],$b['date']));
	$labels=[]; $scores=[]; $ratings=[]; $recs=[];
	foreach ($bucket as $k=>$v) {
	  $labels[]  = $k; // "YYYY-Qn" oder "YYYY-MM"
	  $scores[]  = isset($v['row']['ratingScore']) ? (float)$v['row']['ratingScore'] : null;
	  $ratings[] = (string)($v['row']['rating'] ?? '');
	  $recs[]    = (string)($v['row']['ratingRecommendation'] ?? '');
	}
	// numerisch normalisieren
	$scores = array_map(fn($x)=>is_numeric($x)?(float)$x:null, $scores);
	return [$labels,$scores,$ratings,$recs];
  }
}

// Zeitraum wählen: Quartal default, via ?rating_period=monthly umschaltbar
$RATING_PERIOD = $_GET['rating_period'] ?? 'quarterly'; // 'quarterly' | 'monthly'
[$labels,$scores,$ratings,$recs] = resample_ratings($histList, $RATING_PERIOD);

if (!function_exists('first_row')) {
  function first_row($x){ return (is_array($x) && isset($x[0]) && is_array($x[0])) ? $x[0] : (is_array($x) ? $x : []); }
}
if (!function_exists('latest_by_date')) {
  function latest_by_date(array $rows, $dateKey='date'){
	usort($rows, fn($a,$b)=>strtotime($b[$dateKey]??'')<=>strtotime($a[$dateKey]??''));
	return $rows[0] ?? [];
  }
}

$ptSum    = first_row($ptSumArr);
$latestPT = is_array($ptArr) ? latest_by_date($ptArr, 'publishedDate') : [];

// --- Buy/Hold/Sell Aggregation (nutze NUR die jüngste Recommendation-Zeile) ---
$agg = ['strongBuy'=>0,'buy'=>0,'hold'=>0,'sell'=>0,'strongSell'=>0,'total'=>0];
$consensus = '–';
$consensusDate = '';

// 1) Jüngste Rec-Zeile bestimmen
$latestRec = (is_array($recsArr) && $recsArr) ? latest_by_date($recsArr, 'date') : [];

// 2) Aus der jüngsten Zeile Zähler lesen (case-insensitiv, viele Varianten)
if ($latestRec) {
	// Lowercase-Map für flexible Feldnamen (dein Dump: analystRatingsbuy, analystRatingsHold, ...)
	$lc = [];
	foreach ($latestRec as $k => $v) $lc[strtolower((string)$k)] = $v;

	$maps = [
		// Varianten aus verschiedenen FMP-Endpoints
		'ratingstrongbuy'         => 'strongBuy',
		'ratingbuy'               => 'buy',
		'ratinghold'              => 'hold',
		'ratingsell'              => 'sell',
		'ratingstrongsell'        => 'strongSell',

		'analystratingsstrongbuy' => 'strongBuy',
		'analystratingsbuy'       => 'buy',
		'analystratingshold'      => 'hold',
		'analystratingssell'      => 'sell',
		'analystratingsstrongsell'=> 'strongSell',

		// einfache Formen
		'strongbuy'               => 'strongBuy',
		'buy'                     => 'buy',
		'hold'                    => 'hold',
		'sell'                    => 'sell',
		'strongsell'              => 'strongSell',
	];

	foreach ($maps as $src => $dst) {
		if (isset($lc[$src]) && is_numeric($lc[$src])) {
			$agg[$dst] = (int)$lc[$src];
		}
	}
	$agg['total'] = $agg['strongBuy'] + $agg['buy'] + $agg['hold'] + $agg['sell'] + $agg['strongSell'];

	// Konsens-Datum aus der jüngsten Zeile
	if (!empty($latestRec['date'])) {
		$consensusDate = date('Y-m-d', strtotime($latestRec['date']));
	}
}

// 3) Fallback: falls total == 0, versuche Summary (pt_sum)
if ($agg['total'] === 0 && !empty($ptSum)) {
	$sum = $ptSum; // first_row bereits oben gemacht
	$mapSum = [
		'analystRatingsStrongBuy' => 'strongBuy',
		'analystRatingsBuy'       => 'buy',
		'analystRatingsHold'      => 'hold',
		'analystRatingsSell'      => 'sell',
		'analystRatingsStrongSell'=> 'strongSell',
	];
	foreach ($mapSum as $src => $dst) {
		if (isset($sum[$src]) && is_numeric($sum[$src])) {
			$agg[$dst] = (int)$sum[$src];
		}
	}
	$agg['total'] = $agg['strongBuy'] + $agg['buy'] + $agg['hold'] + $agg['sell'] + $agg['strongSell'];
}

// 4) Konsens bestimmen: zuerst pt_sum['analystConsensus'], sonst Top-Kategorie aus $agg
if (!empty($ptSum['analystConsensus'])) {
	$consensus = (string)$ptSum['analystConsensus'];
} else {
	if ($agg['total'] > 0) {
		$order = $agg; unset($order['total']); arsort($order);
		$top = key($order);
		$mapLabel = ['strongBuy'=>'Strong Buy','buy'=>'Buy','hold'=>'Hold','sell'=>'Sell','strongSell'=>'Strong Sell'];
		$consensus = $mapLabel[$top] ?? ucfirst($top);
	}
}

// 5) In Datencontainer spiegeln (wie zuvor)
$analystData['recommendations']['agg']          = $agg;
$analystData['recommendations']['consensus']    = $consensus;
$analystData['recommendations']['consensusDate']= $consensusDate;

$data_rating['analyst'] = [
	'strongBuy' => $agg['strongBuy'],
	'buy'       => $agg['buy'],
	'hold'      => $agg['hold'],
	'sell'      => $agg['sell'],
];
$data_rating['raw']['analyst'][0]['strongSell'] = $agg['strongSell'];
$data_rating['raw']['analyst'][0]['consensus']  = $consensus;
$data_rating['raw']['analyst'][0]['date']       = $consensusDate;

// Sichtbarkeit der 2. Card: Zähler ODER Consensus-Text reicht
$ptSummary = $analystData['price_targets']['summary'] ?? [];
$hasConsensus = ($agg['total'] > 0) || !empty($ptSummary['analystConsensus']);

// Konsens bestimmen (erst aus Summary, sonst aus Aggregation)
$consensus = '–';
$consensusDate = '';
if (!empty($ptSum['analystConsensus'])) {
	$consensus = (string)$ptSum['analystConsensus'];
} else {
	if ($agg['total'] > 0) {
		$ordered = $agg; unset($ordered['total']); arsort($ordered);
		$top = key($ordered);
		$map = ['strongBuy'=>'Strong Buy','buy'=>'Buy','hold'=>'Hold','sell'=>'Sell','strongSell'=>'Strong Sell'];
		$consensus = $map[$top] ?? ucfirst($top);
	}
}
if (!empty($recsArr)) {
	$latestRec = latest_by_date($recsArr, 'date');
	$consensusDate = !empty($latestRec['date']) ? date('Y-m-d', strtotime($latestRec['date'])) : '';
}

// In $analystData / $data_rating spiegeln (wie bisher)
$analystData['recommendations']['agg'] = $agg;
$analystData['recommendations']['consensus'] = $consensus;
$analystData['recommendations']['consensusDate'] = $consensusDate;

$data_rating['analyst'] = [
	'strongBuy' => $agg['strongBuy'],
	'buy'       => $agg['buy'],
	'hold'      => $agg['hold'],
	'sell'      => $agg['sell'],
];
$data_rating['raw']['analyst'][0]['strongSell'] = $agg['strongSell'];
$data_rating['raw']['analyst'][0]['consensus']  = $consensus;
$data_rating['raw']['analyst'][0]['date']       = $consensusDate;

// Schlichte Konsens-Ableitung (nur für Anzeigezeile)
$consensus = '–';
if ($agg['total'] > 0) {
  $ordered = $agg; unset($ordered['total']);
  arsort($ordered);
  $top = key($ordered);
  // Mapping auf bekannte Labels
  $map = ['strongBuy'=>'Strong Buy','buy'=>'Buy','hold'=>'Hold','sell'=>'Sell','strongSell'=>'Strong Sell'];
  $consensus = $map[$top] ?? ucfirst($top);
}
$consensusDate = '';
if (!empty($recsArr)) {
  $latestRec = latest_by_date($recsArr, 'date');
  $consensusDate = !empty($latestRec['date']) ? date('Y-m-d', strtotime($latestRec['date'])) : '';
}

// Estimates/Earnings optional vorbereiten, wenn Flags aktiv sind
$epsEstimates = []; $revEstimates = [];
if ($HAS_ESTIMATES && is_array($estArr)) {
  foreach ($estArr as $row) {
	if (isset($row['estimatedEPS']) || isset($row['numberAnalystEstimatedEPS'])) $epsEstimates[] = $row;
	if (isset($row['estimatedRevenue']) || isset($row['numberAnalystEstimatedRevenue'])) $revEstimates[] = $row;
  }
  usort($epsEstimates, fn($a,$b)=>strcmp(($b['date']??''), ($a['date']??'')));
  usort($revEstimates, fn($a,$b)=>strcmp(($b['date']??''), ($a['date']??'')));
}

$lastEarning = $nextEarning = [];
if ($HAS_EARNINGS && is_array($earnArr)) {
  $past  = array_filter($earnArr, fn($x)=>!empty($x['date']) && strtotime($x['date'])<=time());
  $future= array_filter($earnArr, fn($x)=>!empty($x['date']) && strtotime($x['date'])> time());
  $lastEarning = latest_by_date($past, 'date');
  $nextEarning = latest_by_date($future, 'date');
}

// Einheitlicher Container (fürs Rendering darunter)
$analystData = [
  'recommendations' => ['series'=>$recsArr, 'agg'=>$agg, 'consensus'=>$consensus, 'consensusDate'=>$consensusDate],
  'price_targets'   => ['latest'=>$latestPT, 'summary'=>first_row($ptSumArr), 'series'=>$ptArr],
  'estimates'       => ['eps'=>$epsEstimates,'revenue'=>$revEstimates,'raw'=>$estArr],
  'earnings'        => ['last'=>$lastEarning,'next'=>$nextEarning,'series'=>$earnArr],
];

// Falls deine bestehende UI $data_rating erwartet, minimal kompatibel befüllen:
$data_rating = $data_rating ?? [];
$data_rating['analyst'] = [
  'strongBuy' => $agg['strongBuy'],
  'buy'       => $agg['buy'],
  'hold'      => $agg['hold'],
  'sell'      => $agg['sell'],
];
$data_rating['raw']['analyst'] = [[
  'consensus'   => $consensus,
  'date'        => $consensusDate,
  'strongSell'  => $agg['strongSell'],
]];

if (!function_exists('rating_color_class')) {
  function rating_color_class($v){ if($v===null)return'secondary'; $s=strtolower(trim((string)$v));
	if(preg_match('/\(([^)]+)\)/',$s,$m)) $s=trim($m[1]); $s=str_replace(['_','-'],' ',$s);
	return match($s){ 'strong buy','buy'=>'success','hold'=>'warning','sell','strong sell'=>'danger', default=>'secondary' };
  }
}

if (!function_exists('consensus_color_class')) {
	function consensus_color_class($consensus) {
		$consensus = strtolower((string)$consensus);
		return match ($consensus) {
			'strong buy' 	=> 'success',
			'buy'        	=> 'success',
			'hold'       	=> 'warning',
			'sell'       	=> 'danger',
			'strong sell'	=> 'dark',
			default      	=> 'secondary',
		};
	}
}
?>

<div class="row mt-2">
	<?php if (!empty($rating)): ?>
	<div class="col-md-6">
		<div class="card">
			<div class="card-body">
				<h5 class="mb-3">Rating</h5>
				<div class="alert alert-<?= rating_color_class($rating['rating']) ?> d-flex justify-content-between align-items-center py-1 px-2">
					<strong><?= htmlspecialchars($rating['rating']) ?> (<?= htmlspecialchars($rating['ratingRecommendation']) ?>)</strong>
					<small>
					  Stand: <?= !empty($rating['date']) 
						  ? htmlspecialchars(date('d.m.Y', strtotime($rating['date']))) 
						  : 'k.A.' ?>
					</small>
				</div>
				<ul class="list-group list-group-flush small">
					<li class="list-group-item px-0">
						<i class="fa-solid fa-circle-info text-muted me-1" data-bs-toggle="tooltip" title="Bewertung aktueller Aktienkurs im Vergleich zum berechneten inneren Wert"></i>
						DCF-Score (Discounted-Cashflow): <strong><?= $rating['ratingDetailsDCFScore'] ?? '–' ?></strong>
					</li>
					<li class="list-group-item px-0">
						<i class="fa-solid fa-circle-info text-muted me-1" data-bs-toggle="tooltip" title="Wie viel Gewinn wird mit dem eingesetzten Eigenkapital erwirtschaftet"></i>
						ROE (Eigenkapitalrendite): <strong><?= $rating['ratingDetailsROEScore'] ?? '–' ?></strong>
					</li>
					<li class="list-group-item px-0">
						<i class="fa-solid fa-circle-info text-muted me-1" data-bs-toggle="tooltip" title="Gewinn im Verhältnis zum gesamten eingesetzten Eigen- und Fremdkapital"></i>
						ROA (Gesamtkapitalrendite): <strong><?= $rating['ratingDetailsROAScore'] ?? '–' ?></strong>
					</li>
					<li class="list-group-item px-0">
						<i class="fa-solid fa-circle-info text-muted me-1" data-bs-toggle="tooltip" title="Verhältnis von Schulden zu Eigenkapital"></i>
						Debt/Equity Score: <strong><?= $rating['ratingDetailsDEScore'] ?? '–' ?></strong>
					</li>
					<li class="list-group-item px-0">
						<i class="fa-solid fa-circle-info text-muted me-1" data-bs-toggle="tooltip" title="Bewertung Aktie im Vergleich zum Gewinn"></i>
						KGV-Score: <strong><?= $rating['ratingDetailsPEScore'] ?? '–' ?></strong>
					</li>
				</ul>
				<canvas id="ratingChart" height="120"></canvas>
			</div>
		</div>
	</div>
	<?php endif; ?>
	
	<?php
		$agg = $analystData['recommendations']['agg'] ?? [];
		$ptSummary = $analystData['price_targets']['summary'] ?? [];
		$hasConsensus = ((int)($agg['total'] ?? 0) > 0) || !empty($ptSummary['analystConsensus']);
	?>
	<?php if ($hasConsensus): ?>
	<div class="col-md-6">
		<div class="card">
			<div class="card-body">
				<h5 class="mb-3">Analysten-Konsens</h5>
				<?php
					$consensusRaw = $data_rating['raw']['analyst'][0] ?? [];
					$consensusText = htmlspecialchars($consensusRaw['consensus'] ?? '–');
					$dateRaw = $consensusRaw['date'] ?? null;
					$dateText = $dateRaw ? date('d.m.Y', strtotime($dateRaw)) : 'k.A.';
					$consensusClass = consensus_color_class($consensusRaw['consensus'] ?? '');
				?>
				<div class="alert alert-<?= $consensusClass ?> d-flex justify-content-between align-items-center py-1 px-2">
					<strong><?= $consensusText ?></strong>
					<small>Stand: <?= $dateText ?></small>
				</div>
				<ul class="list-group list-group-flush small">
					<li class="list-group-item px-0">Strong Buy: <strong><?= $data_rating['analyst']['strongBuy'] ?? 0 ?></strong></li>
					<li class="list-group-item px-0">Buy: <strong><?= $data_rating['analyst']['buy'] ?? 0 ?></strong></li>
					<li class="list-group-item px-0">Hold: <strong><?= $data_rating['analyst']['hold'] ?? 0 ?></strong></li>
					<li class="list-group-item px-0">Sell: <strong><?= $data_rating['analyst']['sell'] ?? 0 ?></strong></li>
					<li class="list-group-item px-0">Strong Sell: <strong><?= $consensusRaw['strongSell'] ?? 0 ?></strong></li>
				</ul>
				<canvas id="analystChart" height="120"></canvas>
			</div>
		</div>
	</div>
	<?php endif; ?>
</div>

<?php if (count(array_filter($scores, 'is_numeric')) >= 2): ?>
<script>
function renderRatingChart() {
  const el = document.getElementById('ratingChart');
  if (!el || typeof Chart === 'undefined') return;

  const ctx = el.getContext('2d');
  new Chart(ctx, {
	type: 'line',
	data: {
	  labels: <?= json_encode($labels) ?>,
	  datasets: [{
		label: 'Rating Score',
		data: <?= json_encode($scores) ?>,
		tension: 0,
		stepped: true,
		fill: false,
		borderWidth: 1.75,
		pointRadius: 2,
		pointHoverRadius: 5,
		backgroundColor: '#000'
	  }]
	},
	options: {
	  scales: { y: { beginAtZero: true, max: 6.0 } },
	  plugins: {
		tooltip: {
		  callbacks: {
			afterLabel: function(ctx) {
			  const i = ctx.dataIndex;
			  const ratings = <?= json_encode($ratings) ?>;
			  const recs    = <?= json_encode($recs) ?>;
			  return (ratings?.[i] && recs?.[i]) ? `Rating: ${ratings[i]} (${recs[i]})` : '';
			}
		  }
		}
	  }
	}
  });
}
if (typeof Chart !== 'undefined') renderRatingChart();
</script>
<?php endif; ?>


<?php if ($hasConsensus): ?>
<script>
function renderAnalystChart() {
  const el = document.getElementById('analystChart');
  if (!el || typeof Chart === 'undefined') return;
  const ctx = el.getContext('2d');
  new Chart(ctx, {
	type: 'bar',
	data: {
	  labels: ['Strong Buy','Buy','Hold','Sell','Strong Sell'],
	  datasets: [{
		label: 'Anzahl Analysten',
		data: [
		  <?= (int)($agg['strongBuy'] ?? 0) ?>,
		  <?= (int)($agg['buy'] ?? 0) ?>,
		  <?= (int)($agg['hold'] ?? 0) ?>,
		  <?= (int)($agg['sell'] ?? 0) ?>,
		  <?= (int)($agg['strongSell'] ?? 0) ?>
		],
		backgroundColor: ['#000', '#000', '#000', '#000', '#000'],
		borderWidth: 1
	  }]
	},
	options: {
	  responsive: true,
	  plugins: { legend:{display:false}, title:{display:true, text:'Analystenmeinung (Konsens)'} },
	  scales: { y: { beginAtZero:true, ticks:{ precision:0 } } }
	}
  });
}
if (typeof Chart !== 'undefined') renderAnalystChart();
</script>
<?php endif; ?>
