<?php
// tabs/tab_strategic_profile.php
$symbol        = $GLOBALS['tab_symbol'] ?? ($_GET['symbol'] ?? '');
$premium_flags = $GLOBALS['premium_flags'] ?? ($_GET['premium_flags'] ?? 0);
$asof          = $_GET['asof'] ?? $_POST['asof'] ?? null;

require_once __DIR__ . '/../../engine/api-handling/fmp_client.php';
require_once __DIR__ . '/../../engine/bewertungsmethoden/bewertung_strategic-profiles.php';
require_once __DIR__ . '/../../engine/bewertungsmethoden/bewertung_fundamental.php';

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

// --- Helper (aus Ausgangsdatei, gekürzt auf das Nötige) ---
function sp_progress_class(float $p): string {
  if ($p >= 80) return 'bg-success';
  if ($p >= 50) return 'bg-warning text-dark';
  return 'bg-danger';
}
function sp_badge_label(string $label): string {
  return preg_replace('/\s*\((grün|gelb|rot)\)\s*$/ui', '', $label) ?? $label;
}
function render_score_card(string $title, array $data): string {
  $p = (float)($data['percent'] ?? 0);
  ob_start(); ?>
	<div class="card mb-3">
		<div class="card-body">
			<div class="mb-2 d-flex justify-content-between align-items-center">
				<h5 class="card-title mb-0"><?= htmlspecialchars($title) ?></h5>
				<span class="fw-semibold"><?= number_format($p,1) ?>%</span>
			</div>
			<div class="progress w-100 mt-2" style="height:10px;">
				<div class="progress-bar <?= sp_progress_class($p) ?>" role="progressbar" style="width: <?= $p ?>%;"></div>
			</div>
			<?php if (!empty($data['why']) && is_array($data['why'])): ?>
				<div class="mt-2">
				<?php foreach ($data['why'] as $w): ?>
					<span class="badge bg-secondary me-1"><?= htmlspecialchars(sp_badge_label($w)) ?></span>
				<?php endforeach; ?>
				</div>
			<?php endif; ?>
		</div>
	</div>
  <?php return ob_get_clean();
}
function render_risk_card(string $title, array $raw): string {
  $profile = $raw['profile'] ?? [];
  $rt      = $raw['rt'] ?? [];
  $km      = $raw['km'] ?? [];
  $hist    = $raw['hist'] ?? [];

  // Helper
  $beta       = $profile['beta'] ?? null;
  $d2e        = $rt['debtToEquityTTM'] ?? null;
  $debtEb     = $rt['netDebtToEBITDATTM'] ?? null;
  $interest   = $km['interestCoverageTTM'] ?? null;
  $current    = $rt['currentRatioTTM'] ?? null;
  $fcfYield   = $rt['freeCashFlowYieldTTM'] ?? null;

  // Drawdown 12M
  $rows = $hist['historical'] ?? $hist;
  $dd12 = null;
  if (is_array($rows) && count($rows) > 0) {
	usort($rows, fn($a,$b)=>strcmp($a['date'] ?? '', $b['date'] ?? ''));
	$closes = array_values(array_filter(array_map(fn($r)=>(float)($r['close'] ?? $r['adjClose'] ?? $r['Close'] ?? 0), $rows)));
	if (count($closes) >= 252) {
	  $slice = array_slice($closes, -252);
	  $peak = $slice[0];
	  $maxDD = 0.0;
	  foreach ($slice as $c) {
		if ($c > $peak) $peak = $c;
		if ($peak > 0) {
		  $dd = ($c/$peak - 1.0) * 100.0;
		  if ($dd < $maxDD) $maxDD = $dd;
		}
	  }
	  $dd12 = $maxDD;
	}
  }

  // Warnungen
  $warn = [];
  if (is_numeric($beta) && $beta > 1.3)                  $warn[] = "Hohe Marktvolatilität (β {$beta})";
  if (is_numeric($debtEb) && $debtEb > 3.0)              $warn[] = "Hebelung erhöht (Debt/EBITDA {$debtEb})";
  if (!is_numeric($debtEb) && is_numeric($d2e) && $d2e>1.5) $warn[] = "Debt/Equity hoch ({$d2e})";
  if (is_numeric($current) && $current < 1.2)            $warn[] = "Schwache Liquidität (Current Ratio {$current})";
  if (is_numeric($fcfYield) && $fcfYield < 0)            $warn[] = "Negativer FCF-Yield";
  if (is_numeric($dd12) && $dd12 < -25)                  $warn[] = "Starker 12M Drawdown (" . number_format($dd12,1) . "%)";
  if (is_numeric($interest) && $interest > 0 && $interest < 5) $warn[] = "Geringe Zinsdeckung (" . number_format($interest,2) . "x)";

  ob_start(); ?>
  <div class="alert alert-danger mb-3">
	  <h5><?= htmlspecialchars($title) ?></h5>
	  <?php if ($warn): ?>
		<div class="mb-0">
		  <?php foreach ($warn as $w): ?>
		  <span class="badge bg-danger me-1 mb-1"><?= htmlspecialchars($w) ?></span>
		  <?php endforeach; ?>
		</div>
	  <?php else: ?>
		<p class="mb-0">Keine auffälligen Risikosignale anhand der Basis-Metriken.</p>
	  <?php endif; ?>
  </div>
  <?php return ob_get_clean();
}
function render_summary(array $hp, array $sol, array $erg, array $raw, float $fundPercent, float $stratPercent): string {
  $prof   = $raw['profile'] ?? [];
  $name   = $prof['companyName'] ?? $prof['company-name'] ?? '';
  $sector = $prof['sector'] ?? '';
  ob_start(); ?>
  <div class="card">
	<div class="card-body">
	  <h5 class="card-title mb-1"><?= htmlspecialchars($name) ?></h5>
	  <?php if ($sector): ?><div class="text-muted small mb-2"><?= htmlspecialchars($sector) ?></div><?php endif; ?>
	  <div class="d-flex flex-wrap gap-3">
		<div>Fundamental: <strong><?= number_format($fundPercent,1) ?>%</strong></div>
		<div>Strategic: <strong><?= number_format($stratPercent,1) ?>%</strong></div>
		<div><strong>⌀ <?= number_format(($fundPercent + $stratPercent)/2, 1) ?>%</strong></div>
	  </div>
	</div>
  </div>
  <?php return ob_get_clean();
}

// --- Daten laden (Multi-Fetch in den Bewertungsfunktionen) ---
$premium = !empty($premium_flags);

$hp  = bewertung_strategic_profiles_score($symbol, 'high_performer', ['premium'=>$premium]);
$sol = bewertung_strategic_profiles_score($symbol, 'solide',          ['premium'=>$premium]);
$erg = bewertung_strategic_profiles_score($symbol, 'ertragreich',     ['premium'=>$premium]);
$raw = bewertung_strategic_profiles_fetch($symbol, ['premium'=>$premium]);

$resFund   = bewertung_fundamental_score($symbol, $asof, null, null, ['enable_pe_fallback'=>false]);
$fundScore = (isset($resFund['percent']) && is_numeric($resFund['percent'])) ? (float)$resFund['percent'] : 0.0;

// Strategic-Composite + Frühsignal (wie in Ausgangsdatei)
$sp_y_base = max((float)($hp['percent'] ?? 0), (float)($sol['percent'] ?? 0), (float)($erg['percent'] ?? 0));
$closes    = sp_extract_closes($raw['hist'] ?? []); // kommt aus bewertung_strategic-profiles.php
$lastPx    = !empty($closes) ? end($closes) : null;
$sma200    = null;
if (count($closes) >= 200) { $sum=0; for ($i=count($closes)-200; $i<count($closes); $i++) $sum += $closes[$i]; $sma200=$sum/200; }
$mom1m     = (count($closes)>=22 && $closes[count($closes)-22]>0) ? ((($closes[count($closes)-1]/$closes[count($closes)-22])-1)*100) : null;
$mom3m     = (count($closes)>=64 && $closes[count($closes)-64]>0) ? ((($closes[count($closes)-1]/$closes[count($closes)-64])-1)*100) : null;

$earlySignal=false;
if ($mom1m !== null && $mom3m !== null && $lastPx !== null && $sma200 !== null) {
  $above200 = ($lastPx >= 0.97*$sma200);
  $fastMom  = ($mom1m >= 15) || ($mom3m >= 25);
  if ($fastMom && $above200) $earlySignal = true;
}
$sp_y = $sp_y_base;
if ($earlySignal && $sp_y_base < 40) $sp_y = 40;
if ($earlySignal && $sp_y < 60) {
  $strength = min(1.0, max(0.0, max(($mom1m??0)/25.0, ($mom3m??0)/35.0)));
  $sp_y = min(60, $sp_y + 10 + 10*$strength);
}

$prof         = $raw['profile'] ?? [];
$companyLabel = ($prof['companyName'] ?? $symbol) . " ({$symbol})";
$sector       = $prof['sector'] ?? null;

// Chart-Punkt + Farbe analog Original
$ptColor = 'rgba(220,53,69,0.9)';
if ($fundScore >= 75 && $sp_y >= 60)      $ptColor = 'rgba(0,128,0,0.9)';
elseif ($fundScore >= 75)                 $ptColor = 'rgba(0,102,204,0.9)';
elseif ($sp_y >= 60)                      $ptColor = 'rgba(255,165,0,0.9)';

$chartPoint = [
  'x'=>round($fundScore,2),
  'y'=>round($sp_y,2),
  'r'=>$earlySignal?8:6,
  'c'=>$ptColor,
  'label'=>$companyLabel,
  'sector'=>$sector,
  'hint'=>implode(' · ', array_filter([
	isset($mom1m)?('1M: '.number_format($mom1m,1).'%' ):null,
	isset($mom3m)?('3M: '.number_format($mom3m,1).'%' ):null,
	($sma200 && $lastPx)?('Preis/SMA200: '.number_format($lastPx/$sma200*100,1).'%'):null,
	$earlySignal?'Early Signal: ✓':null,
  ])),
  'glow'=>$earlySignal,
];
?>
<div class="row g-3">
  <div class="col-md-5">
	<?= render_summary($hp,$sol,$erg,$raw,(float)$fundScore,(float)$sp_y) ?>
	<div class="card mt-3">
	  <div class="card-body">
		<h5 class="card-title mb-0">Fundamental × Strategic Matrix</h5>
		<p class="text-muted mb-2">Frühsignal-Modus (1M/3M Momentum)</p>
		<div class="height-150"><canvas id="fundStratMatrix" height="150"></canvas></div>
	  </div>
	</div>
  </div>
  <div class="col-md-7">
	  <?= render_score_card('High-Performer', $hp) ?>
	  <?= render_score_card('Solide Investments', $sol) ?>
	  <?= render_score_card('Ertragreiche Investments', $erg) ?>
	  <?= render_risk_card('Risiko-Check', $raw) ?>
	</div>
</div>

<script>
window.renderStrategicProfileChart = function(){
  var el = document.getElementById('fundStratMatrix');
  if (!el || typeof Chart === 'undefined') return;
  var ctx = el.getContext('2d');
  var pt  = <?= json_encode($chartPoint, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;

  var bgPlugin = {
	id:'bgPlugin',
	beforeDraw(chart){
	  var a = chart.chartArea, scales = chart.scales, ctx = chart.ctx; if(!a) return;
	  var x75 = scales.x.getPixelForValue(75), y60 = scales.y.getPixelForValue(60);
	  ctx.save();
	  ctx.fillStyle='rgba(220,53,69,0.04)'; ctx.fillRect(a.left, y60, x75-a.left, a.bottom-y60);
	  ctx.fillStyle='rgba(0,102,204,0.06)'; ctx.fillRect(x75, y60, a.right-x75, a.bottom-y60);
	  ctx.fillStyle='rgba(255,165,0,0.05)'; ctx.fillRect(a.left, a.top, x75-a.left, y60-a.top);
	  ctx.fillStyle='rgba(0,128,0,0.06)';   ctx.fillRect(x75, a.top, a.right-x75, y60-a.top);
	  ctx.strokeStyle='rgba(0,0,0,0.15)'; ctx.setLineDash([6,6]);
	  ctx.beginPath(); ctx.moveTo(x75,a.top); ctx.lineTo(x75,a.bottom); ctx.stroke();
	  ctx.beginPath(); ctx.moveTo(a.left,y60); ctx.lineTo(a.right,y60); ctx.stroke();
	  ctx.restore();
	}
  };

  new Chart(ctx, {
	type:'scatter',
	data:{ datasets:[{
	  data:[{x:pt.x,y:pt.y}],
	  parsing:false,
	  pointRadius:function(){return pt.r},
	  pointHoverRadius:10,
	  pointBackgroundColor:function(){return pt.c},
	  pointBorderColor:function(){return pt.glow?'rgba(0,0,0,0.6)':'rgba(0,0,0,0.3)'},
	  pointBorderWidth:function(){return pt.glow?3:1.5}
	}]},
	options:{
	  responsive:true, maintainAspectRatio:false,
	  scales:{
		x:{suggestedMin:0,suggestedMax:100,title:{display:true,text:'Fundamental-Score (0–100)'}},
		y:{suggestedMin:0,suggestedMax:100,title:{display:true,text:'Strategic-Score (0–100)'}}
	  },
	  plugins:{
		legend:{display:false},
		tooltip:{callbacks:{label:function(){return [pt.label, pt.sector?('Branche: '+pt.sector):null, pt.hint].filter(Boolean)}}}
	  },
	  elements:{point:{hitRadius:6}}
	},
	plugins:[bgPlugin]
  });
};

if (typeof renderStrategicProfileChart === 'function') renderStrategicProfileChart();
</script>
