<?php
require_once __DIR__ . '/engine/engine.php';
require_once __DIR__ . '/engine/api-handling/fmp_client.php';
$requires_search = true;
$requires_chartjs = true;
require_once __DIR__ . '/views/header.php';
require_once __DIR__ . '/views/navigation.php';


$symbol_input    = $_GET['symbol']     ?? '';
$asof_input      = $_GET['asof']       ?? '';
$target_pe_input = $_GET['target_pe']  ?? '';

$symbol = $symbol_input ? strtoupper(trim($symbol_input)) : null;
?>
<main class="flex-grow-1">
	<div class="container pb-5">
		<div class="sticky-top mt-5 bg-white z-3 pb-4">
			<div class="d-flex justify-content-between">
				<h1 class="mb-4">Aktienbewertung</h1>
				<div>
				<?php
					if ($symbol) {
						$category = 'Fundamental';
						include 'execute/watchlist/watchlist_button.php';
					}
				?>
				</div>
			</div>
			<form method="get">
				<div class="row g-2">
					<div class="col-md-4">
						<input type="text" name="symbol" placeholder="Symbol" class="form-control symbol-autocomplete" value="<?= htmlspecialchars($symbol ?? '') ?>" required>
					</div>
					<div class="col-md-4">
						<input type="number" step="0.1" name="target_pe" placeholder="Branchen-KGV" class="form-control" value="<?= htmlspecialchars($target_pe_input) ?>">
					</div>
					<div class="col-md-4">
						<input type="date" name="asof" class="form-control" placeholder="Stichtag" value="<?= htmlspecialchars($asof_input) ?>">
					</div>
					<div class="col-12">
						<button type="submit" class="btn btn-dark w-100 mt-2">Analysieren</button>
					</div>
				</div>
			</form>
		</div>
			
		<?php if ($symbol): ?>
			<div class="row">
				<div class="col-12">
					<ul class="nav nav-tabs mb-3" id="evaluationTabs" role="tablist">
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark active" data-group="fundamental_basic" data-bs-toggle="tab" data-bs-target="#tab-fundamental" role="tab">Bewertung</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="profile" data-bs-toggle="tab" data-bs-target="#tab-profile" role="tab">Profil</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="strategic-profile" data-bs-toggle="tab" data-bs-target="#tab-strategic-profile" role="tab">S-Profil</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="technical" data-bs-toggle="tab" data-bs-target="#tab-technical" role="tab">Chart</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="berichte" data-bs-toggle="tab" data-bs-target="#tab-berichte" role="tab">Berichte</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="analyst_rating" data-bs-toggle="tab" data-bs-target="#tab-analyst" role="tab">Analysten</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="dividends" data-bs-toggle="tab" data-bs-target="#tab-dividends" role="tab">Dividenden</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="insider" data-bs-toggle="tab" data-bs-target="#tab-insider" role="tab">Insider</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="news" data-bs-toggle="tab" data-bs-target="#tab-news" role="tab">News</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="seasonality" data-bs-toggle="tab" data-bs-target="#tab-seasonality" role="tab">Saisonalität</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="minervini" data-bs-toggle="tab" data-bs-target="#tab-minervini" role="tab">Minervini</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="korrelationen" data-bs-toggle="tab" data-bs-target="#tab-korrelationen" role="tab">Korrelationen</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link text-dark" data-group="forecast" data-bs-toggle="tab" data-bs-target="#tab-forecast" role="tab">Forecast</button>
						</li>
					</ul>
				</div>
			</div>
		
			<div class="tab-content mt-3">
				<div class="tab-pane fade show active" id="tab-fundamental" data-loaded="false">
					<div class="text-center text-muted py-4" id="loading-fundamental">
						<div class="spinner-border text-dark" role="status"></div>
						<div>Lade Daten …</div>
					</div>
				</div>
				<div class="tab-pane fade" id="tab-analyst" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-profile" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-strategic-profile" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-technical" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-berichte" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-analyst" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-dividends" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-insider" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-news" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-seasonality" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-minervini" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-korrelationen" data-loaded="false"></div>
				<div class="tab-pane fade" id="tab-forecast" data-loaded="false"></div>
			</div>
		<?php endif; ?>
		
	</div>
</main>

<?php if ($symbol): ?>
<script>
const currentSymbol = "<?= htmlspecialchars($symbol_input ?? '') ?>";
const currentAsof   = "<?= htmlspecialchars($asof_input ?? '') ?>";
const target_pe     = "<?= htmlspecialchars($target_pe_input ?? '') ?>";

function initTooltips(scope) {
  const root = scope || document;
  root.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
	const inst = bootstrap.Tooltip.getInstance(el);
	if (inst) inst.dispose();
	new bootstrap.Tooltip(el);
  });
}

async function loadTabContent(group, targetId, symbol, asof) {
  const target = document.querySelector(targetId);
  if (!target || target.dataset.loaded === 'true') return;

  const params = new URLSearchParams({
	symbol: symbol || '',
	group: group || '',
	asof:  asof || '',
	target_pe: target_pe || ''
  });
  const url = `/execute/aktienbewertung/load_tab_group.php?` + params.toString();

  try {
	target.innerHTML = '<div class="text-center py-3"><div class="spinner-border" role="status"></div></div>';
	const res = await fetch(url, { credentials: 'same-origin' });
	if (!res.ok) throw new Error("Serverfehler: " + res.status);
	const html = await res.text();

	target.innerHTML = html;

	const scripts = Array.from(target.querySelectorAll('script'));
	for (const old of scripts) {
	  const s = document.createElement('script');
	  if (old.type) s.type = old.type; // z.B. "module"
	  if (old.src) {
		s.src = old.src;
		s.async = false; // Reihenfolge sicherstellen
		await new Promise((resolve, reject) => {
		  s.onload = resolve; s.onerror = reject;
		  document.head.appendChild(s);
		});
	  } else {
		s.textContent = old.textContent;
		document.head.appendChild(s);
		document.head.removeChild(s);
	  }
	}

	initTooltips(target);
	target.dataset.loaded = 'true';

  } catch (err) {
	target.innerHTML = `<div class="alert alert-danger">Fehler beim Laden von <code>${group}</code></div>`;
	console.error("Fehler beim Laden:", err);
  }
}

document.addEventListener('shown.bs.tab', () => {
  document.querySelectorAll('canvas').forEach(cv => {
	const inst = (window.Chart && Chart.getChart) ? Chart.getChart(cv) : null;
	if (inst && inst.resize) inst.resize();
  });
});

document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('[data-bs-toggle="tab"]').forEach(btn => {
	btn.addEventListener('shown.bs.tab', async () => {
	  const group = btn.getAttribute('data-group');
	  const targetId = btn.getAttribute('data-bs-target');
	  await loadTabContent(group, targetId, currentSymbol, currentAsof);
	  document.dispatchEvent(new CustomEvent('ajaxTabLoaded', { detail: { targetId } }));
	});
  });
});

window.addEventListener('load', async () => {
  const group = 'fundamental_basic';
  const targetId = '#tab-fundamental';
  await loadTabContent(group, targetId, currentSymbol, currentAsof);
  document.dispatchEvent(new CustomEvent('ajaxTabLoaded', { detail: { targetId } }));
});
</script>
<?php endif; ?>

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