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


$lists = fmp_multi(['sectors'=>['key'=>'sectors_list']]); // nur Sektoren initial
$sectors = array_values(array_filter((array)($lists['sectors'] ?? [])));
if (!$sectors) $sectors = ['Technology','Financial Services','Healthcare','Industrials'];

?>

<main class="flex-grow-1">
	<div class="container my-5">
		<h1>Aktien-Screener</h1>
		<form id="scanForm" class="row g-3">
			<div class="col-12 col-md-3">
				<label class="form-label">Sektor</label>
				<select class="form-select" name="sector" id="sector">
				<?php foreach($sectors as $s): ?>
					<option value="<?=htmlspecialchars($s)?>" <?= $s==='Technology'?'selected':''; ?>><?=htmlspecialchars($s)?></option>
				<?php endforeach; ?>
				</select>
			</div>
			<div class="col-12 col-md-3">
				<label class="form-label">Industrie</label>
				<select class="form-select" name="industry" id="industry"><option value="">— alle —</option></select>
			</div>
			<div class="col-6 col-md-3">
				<label class="form-label">Land</label>
				<select class="form-select" name="country" id="country"><option value="">— alle —</option></select>
			</div>
			<div class="col-6 col-md-3">
				<label class="form-label">Börse</label>
				<select class="form-select" name="exchange" id="exchange"><option value="">— alle —</option></select>
			</div>
			<div class="col-6 col-md-3">
				<label class="form-label">Bewertungsmethode</label>
				<select class="form-select" name="agg" id="agg">
					<option value="">Ø (Mean)</option>
					<option value="median">Median</option>
				</select>
			</div>
			<div class="col-6 col-md-3">
				<label class="form-label">P/E Floor</label>
				<input type="number" step="0.1" min="0" name="pe_floor" value="5" class="form-control" />
			</div>
			<div class="col-6 col-md-3">
				<label class="form-label">Min. ROIC (%)</label>
				<input type="number" step="0.1" name="min_roic" value="0" class="form-control" />
			</div>
			<div class="col-6 col-md-3">
				<label class="form-label">Ausschluss-Keywords</label>
				<input type="text" name="exclude" placeholder="Symbol oder Keyword" class="form-control" />
			</div>
			<div class="col-6">
				<label class="form-check form-switch">
					<input class="form-check-input" type="checkbox" id="onlyHits" checked>
					<span class="form-check-label">Nur Werte anzeigen über ⌀ EPS & E/P</span>
				</label>
			</div>
			<div class="col-6">
				<div class="form-check form-switch mb-0">
					<input class="form-check-input" type="checkbox" id="use_defaults" checked>
					<label class="form-check-label" for="use_defaults">Sektor-Defaults verwenden (P/E Floor & Min. ROIC)</label>
				</div>
				<small id="defaultsHint" class="text-muted"></small>
			</div>
			<div class="col-12">
				<button class="btn btn-dark w-100" id="startBtn">Scan starten</button>
				<div id="modeBadge" class="mt-3 badge rounded-pill bg-light text-dark d-none"></div>
				<div id="stats" class="mt-2 align-self-center small text-muted"></div>
			</div>
		</form>
	
		<div id="averagesBox" class="mt-3 d-none"></div>
	
		<div class="table-responsive mt-3 d-none" id="tableWrap">
			<table class="table" id="results">
				<thead class="table-dark">
					<tr>
						<th>Symbol</th>
						<th>Name</th>
						<th>Industry</th>
						<th>Country</th>
						<th>Exchange</th>
						<th>Price</th>
						<th>P/E (Fwd/TTM)</th>
						<th>EPS (FY1/TTM)</th>
						<th>Score</th>
						<th>Factors</th>
						<th>MCap</th>
					</tr>
				</thead>
				<tbody></tbody>
			</table>
		</div>
		
		<button
			class="btn btn-outline-secondary btn-sm mb-2 mt-4"
			type="button"
			data-bs-toggle="collapse"
			data-bs-target="#defaults-table"
			aria-expanded="false"
			aria-controls="defaults-table">
			Sektor-Defaults (P/E Floor & Min. ROIC)
		</button>
		<div class="collapse" id="defaults-table">
			<div class="table-responsive">
				<table class="table table-sm table-bordered align-middle mb-0">
					<thead class="table-dark">
						<tr>
						<th>Sektor</th>
						<th class="text-end">P/E Floor</th>
						<th class="text-end">Min. ROIC (%)</th>
						</tr>
					</thead>
					<tbody>
						<tr><td>Technology</td>    <td class="text-end">15</td><td class="text-end">12</td></tr>
						<tr><td>Healthcare</td>    <td class="text-end">10</td><td class="text-end">10</td></tr>
						<tr><td>Financial</td>     <td class="text-end">6</td><td class="text-end">8</td></tr>
						<tr><td>Energy</td>        <td class="text-end">5</td><td class="text-end">8</td></tr>
						<tr><td>Materials</td>     <td class="text-end">8</td><td class="text-end">8</td></tr>
						<tr><td>Industrials</td>   <td class="text-end">10</td><td class="text-end">10</td></tr>
						<tr><td>Consumer</td>      <td class="text-end">12</td><td class="text-end">10</td></tr>
						<tr><td>Utilities</td>     <td class="text-end">8</td><td class="text-end">6</td></tr>
						<tr><td>Real Estate</td>   <td class="text-end">8</td><td class="text-end">6</td></tr>
						<tr><td>Communication</td> <td class="text-end">10</td><td class="text-end">8</td></tr>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</main>

<script>
document.addEventListener('DOMContentLoaded', function () {
  (function () {
	// ---------------------- Config: Sektor-Defaults ----------------------
	const SECTOR_THRESHOLDS = {
	  technology:{pe_floor:15, min_roic:12},
	  healthcare:{pe_floor:10, min_roic:10},
	  financial:{pe_floor:6,  min_roic:8},
	  energy:{pe_floor:5, min_roic:8},
	  materials:{pe_floor:8, min_roic:8},
	  industrials:{pe_floor:10, min_roic:10},
	  consumer:{pe_floor:12, min_roic:10},
	  utilities:{pe_floor:8, min_roic:6},
	  "real estate":{pe_floor:8, min_roic:6},
	  communication:{pe_floor:10, min_roic:8},
	};

	// ---------------------- DOM Refs ----------------------
	const form        = document.getElementById('scanForm');
	const startBtn    = document.getElementById('startBtn');
	const stats       = document.getElementById('stats');
	const modeBadge   = document.getElementById('modeBadge');
	const avgBox      = document.getElementById('averagesBox');
	const tableWrap   = document.getElementById('tableWrap');
	const tbody       = document.querySelector('#results tbody');

	const sectorSel   = document.getElementById('sector');
	const peFloorInp  = document.getElementById('pe_floor');
	const roicInp     = document.getElementById('min_roic');
	const industrySel = document.getElementById('industry');
	const countrySel  = document.getElementById('country');
	const exchangeSel = document.getElementById('exchange');
	const aggSel      = document.getElementById('agg');
	const onlyHits    = document.getElementById('onlyHits');
	const useDefaults = document.getElementById('useDefaults'); // Bootstrap Switch (optional)

	// ---------------------- Utils ----------------------
	const f2 = v => (v==null || isNaN(v)) ? '–' : Number(v).toFixed(2);
	const f3 = v => (v==null || isNaN(v)) ? '–' : Number(v).toFixed(3);
	const esc = s => String(s ?? '').replace(/[&<>"']/g, c => (
	  { '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]
	));

	function factorBadge(label, val, hint) {
	  if (val==null || isNaN(val)) return '';
	  let cls = 'bg-secondary';
	  if (val >= 0.66) cls = 'bg-success';
	  else if (val >= 0.33) cls = 'bg-primary';
	  return `<span class="badge ${cls} me-1" title="${hint||''}">${label}: ${f2(val*100)}%</span>`;
	}

	async function apiGet(path, params = {}) {
	  const url = new URL(path, window.location.origin);
	  Object.entries(params).forEach(([k,v]) => { if (v!=='' && v!=null) url.searchParams.set(k, v); });
	  const res = await fetch(url.toString(), { credentials:'same-origin' });
	  const raw = await res.text();
	  try { return JSON.parse(raw); }
	  catch(e){
		avgBox.classList.remove('d-none');
		avgBox.innerHTML = `<div class="alert alert-danger"><strong>Fehler:</strong> Ungültige Server-Antwort.<pre style="white-space:pre-wrap;max-height:260px;overflow:auto;margin:0">${esc(raw)}</pre></div>`;
		throw e;
	  }
	}

	function fillSelectPreserve(sel, items, placeholder) {
	  if (!sel) return;
	  const prev = sel.value;
	  sel.innerHTML = `<option value="">${placeholder||'— alle —'}</option>` +
		(items||[]).map(v => `<option value="${String(v)}">${String(v)}</option>`).join('');
	  if (prev && Array.from(sel.options).some(o => o.value === prev)) sel.value = prev;
	}

	function resetUI() {
	  stats.textContent = '';
	  modeBadge.classList.add('d-none'); modeBadge.textContent = '';
	  avgBox.classList.add('d-none');    avgBox.innerHTML = '';
	  tbody.innerHTML = '';
	  tableWrap.classList.add('d-none');
	  if (window.jQuery && jQuery.fn.dataTable && $.fn.dataTable.isDataTable('#results')) {
		$('#results').DataTable().destroy();
	  }
	}
	
	function ensureStatsParts() {
	  // Spinner vorbereiten (falls nicht vorhanden)
	  let spinner = document.getElementById('scanSpinner');
	  if (!spinner) {
		spinner = document.createElement('span');
		spinner.id = 'scanSpinner';
		spinner.innerHTML = `<div class="spinner-border spinner-border-sm text-black me-2" role="status"></div>`;
		stats.prepend(spinner);
	  }
	  // Text-Span vorbereiten (damit wir nicht stats.innerHTML überschreiben)
	  let textEl = document.getElementById('statsText');
	  if (!textEl) {
		textEl = document.createElement('span');
		textEl.id = 'statsText';
		stats.appendChild(textEl);
	  }
	  return { spinner, textEl };
	}
	
	function toggleSpinner(show) {
	  const { spinner } = ensureStatsParts();
	  spinner.style.display = show ? 'inline-block' : 'none';
	}
	
	function setStatsText(text) {
	  const { textEl } = ensureStatsParts();
	  textEl.textContent = text || '';
	}

	// ---------------------- Defaults-Handling ----------------------
	function setThresholdsFromSector(overwrite = false) {
	  const k = (sectorSel?.value || '').toLowerCase();
	  const t = SECTOR_THRESHOLDS[k];
	  if (!t) return;
	  const write = (inp, val) => {
		if (!inp) return;
		const v = Number(val);
		if (!Number.isFinite(v)) return;
		if (overwrite || inp.value === '' || inp.value == null) inp.value = v;
	  };
	  write(peFloorInp, t.pe_floor);
	  write(roicInp,  t.min_roic);

	  const lock = !!(useDefaults && useDefaults.checked);
	  if (peFloorInp) peFloorInp.disabled = lock;
	  if (roicInp)    roicInp.disabled    = lock;
	}

	function prefillThresholds() {
	  setThresholdsFromSector(!!(useDefaults && useDefaults.checked));
	}

	// ---------------------- Meta / Live-Zähler ----------------------
	let metaItems = []; // aus sector_meta.php
	let lastAll   = []; // items_all der letzten Abfrage

	function liveFilterCount() {
	  const ind = (industrySel?.value||'').toLowerCase();
	  const ctr = (countrySel?.value||'').toLowerCase();
	  const ex  = (exchangeSel?.value||'').toLowerCase();
	  const match = (h, n) => !n || (h||'').toLowerCase().includes(n);
	  const base = metaItems.length;
	  const count = metaItems.filter(m => match(m.industry, ind) && match(m.country, ctr) && match(m.exchange, ex)).length;
	  stats.textContent = `Screener-Basis: ${base} | nach Auswahl: ${count}`;
	}

	async function loadMetaForCurrentSector() {
	  resetUI();
	  const sector = sectorSel?.value || '';
	  if (!sector) { stats.textContent = 'Bitte Sektor wählen.'; return; }

	  stats.textContent = 'Lade Metadaten…';
	  const meta = await apiGet('/execute/aktien-screener/sector_meta.php', { sector });
	  fillSelectPreserve(industrySel, meta.industries || [], '— alle —');
	  fillSelectPreserve(countrySel,  meta.countries  || [], '— alle —');
	  fillSelectPreserve(exchangeSel, meta.exchanges  || [], '— alle —');

	  metaItems = meta.items_meta || [];
	  stats.textContent = `Screener-Basis: ${meta.counts?.screener || metaItems.length || 0}`;
	  liveFilterCount();
	}

	// ---------------------- Averages / Tabelle ----------------------
	function renderAveragesBox(data) {
	  const av = data.averages || {};
	  const agg = av.agg ? av.agg.toUpperCase() : (aggSel?.value==='median' ? 'MEDIAN' : 'Ø');

	  if (data.mode === 'forward') {
		modeBadge.textContent = 'Forward Mode';
		modeBadge.classList.remove('d-none','bg-secondary');
		modeBadge.classList.add('bg-info');
		avgBox.innerHTML = `
		  <div class="alert alert-warning py-2 px-3 mb-3">
			<strong>Durchschnitte (${agg})</strong> — Fwd P/E: ${f2(av.pe_fwd)} | EPS Growth (FY1E): ${f2(av.eps_growth)}
		  </div>`;
	  } else {
		modeBadge.textContent = 'TTM Mode';
		modeBadge.classList.remove('d-none','bg-info');
		modeBadge.classList.add('bg-secondary');
		avgBox.innerHTML = `
		  <div class="alert alert-light text-dark py-2 px-3 mb-2">
			<strong>Durchschnitte (${agg})</strong> — P/E (TTM): ${f2(av.pe)} | EPS (TTM): ${f2(av.eps)}
		  </div>`;
	  }
	  avgBox.classList.remove('d-none');
	}

	function renderRowsAll(items, onlyHitsFlag = false) {
	  lastAll = Array.isArray(items) ? items : [];
	  const list = onlyHitsFlag ? lastAll.filter(r => r.isHit) : lastAll;
	
	  tbody.innerHTML = '';
	  for (const r of list) {
		const tr = document.createElement('tr'); // <-- fehlte
	
		const symbolHtml = r.isHit
		  ? `<span class="fw-bold">${r.symbol ?? ''}</span>`
		  : `<span class="fw-normal">${r.symbol ?? ''}</span>`;
	
		const factorsHTML = [
		  factorBadge('Growth',  r.scoreGrowth,  'Perzentil innerhalb der Sub-Industry (höher besser)'),
		  factorBadge('Value',   r.scoreValue,   '1 − P/E-Perzentil (niedrigeres P/E besser)'),
		  factorBadge('Quality', r.scoreQuality, 'Ø aus ROIC, Gross, FCF-Marge')
		].join('');
	
		tr.innerHTML = `
		  <td>${symbolHtml}</td>
		  <td class="fw-bold">${r.name ?? ''}</td>
		  <td>${r.industry ?? ''}</td>
		  <td>${r.country ?? ''}</td>
		  <td>${r.exchange ?? ''}</td>
		  <td>${r.price ?? ''}</td>
		  <td>${r.pe_fwd ?? r.pe ?? ''}</td>
		  <td>${(r.eps_fy1 ?? r.eps) ?? ''}</td>
		  <td><strong>${f3(r.score)}</strong></td>
		  <td>${factorsHTML}</td>
		  <td>${r.marketCapFmt ?? ''}</td>
		`;
		tbody.appendChild(tr);
	  }
	
	  if (list.length) {
		tableWrap.classList.remove('d-none');
		if (window.jQuery && jQuery.fn.dataTable) {
		  if ($.fn.dataTable.isDataTable('#results')) $('#results').DataTable().destroy();
		  $('#results').DataTable({ pageLength: 25, order: [[8,'desc']] }); // Spalte 8 = Score
		}
	  } else {
		tableWrap.classList.add('d-none');
	  }
	}

	// ---------------------- Events ----------------------
	sectorSel?.addEventListener('change', () => {
	  prefillThresholds();
	  loadMetaForCurrentSector();
	});
	useDefaults?.addEventListener('change', () => setThresholdsFromSector(true));
	[industrySel, countrySel, exchangeSel].forEach(sel => sel?.addEventListener('change', liveFilterCount));
	onlyHits?.addEventListener('change', () => renderRowsAll(lastAll, !!onlyHits.checked));

	form?.addEventListener('submit', async (e) => {
	  e.preventDefault();
	  resetUI();
	  startBtn && (startBtn.disabled = true);
	
	  toggleSpinner(true);
	  setStatsText('Scan läuft…');
	
	  const params = Object.fromEntries(new FormData(form).entries());
	  if (aggSel && aggSel.value) params.agg = aggSel.value;
	
	  const data = await apiGet('/execute/aktien-screener/sector_scan.php', params);
	
	  toggleSpinner(false);
	  setStatsText(`Screener: ${data.counts?.screener||0} | nach Filter: ${data.counts?.after_local||0} | Quotes: ${data.counts?.quotes||0} | Treffer: ${data.counts?.filtered||0}`);
	  renderAveragesBox(data);
	  renderRowsAll(data.items_all || [], !!onlyHits?.checked);
	
	  startBtn && (startBtn.disabled = false);
	});

	// ---------------------- Initial ----------------------
	if (aggSel) aggSel.value = 'median';
	prefillThresholds();           // setzt ggf. Default-Werte und sperrt Inputs bei Toggle=on
	loadMetaForCurrentSector();    // lädt die Metadaten für den aktuellen Sektor
  })();
});
</script>

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