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

$ratingCriteria = [
	"Fundamentale Stärke",
	"Marktkapitalisierung über 3 Mrd.",
	"Saisonal stark",
	"Minervini Kriterien erfüllt",
	"Oversold",
	"Zahlt Dividenden",
	"Keine Earnings in naher Zukunft",
	"Insider kaufen",
	"Positive Analysten-Ratings"
];
$maxScore = count($ratingCriteria);

$stmt = $pdo->query("
	SELECT 
		symbol, 
		GROUP_CONCAT(category ORDER BY category SEPARATOR ', ') AS categories,
		MAX(note) AS note,
		MAX(rating_criteria) AS rating_criteria,
		MIN(added_at) AS added_at
	FROM watchlist
	GROUP BY symbol
	ORDER BY symbol
");
$entries = $stmt->fetchAll();

$markedSymbols = $pdo->query("SELECT DISTINCT symbol FROM watchlist WHERE is_marked = 1")->fetchAll(PDO::FETCH_COLUMN);
?>

<main class="flex-grow-1 container my-5">
	<h1 class="mb-4">Watchlist</h1>

	<div class="table-responsive">
		<table class="table" id="watchlistTable">
			<thead class="table-dark">
				<tr>
					<th style="width:30px;"></th>
					<th>Symbol</th>
					<th>Performance</th>
					<th>Kategorien</th>
					<th>Notiz</th>
					<th>Rating</th>
					<th>Löschen</th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ($entries as $row): ?>
					<?php $isMarked = in_array($row['symbol'], $markedSymbols); ?>
					<tr data-symbol="<?= htmlspecialchars($row['symbol']) ?>" class="align-middle">
						<td>
							<i class="fa-solid fa-bookmark toggle-mark <?= $isMarked ? 'text-danger' : 'text-secondary' ?>"
							   style="cursor:pointer;"
							   data-symbol="<?= htmlspecialchars($row['symbol']) ?>"
							   data-marked="<?= $isMarked ? '1' : '0' ?>">
							</i>
						</td>
						<td>
							<a href="/aktienbewertung.php?symbol=<?= htmlspecialchars($row['symbol']) ?>" target="_blank" rel="noopener" class="text-dark text-decoration-none">
								<strong><?= htmlspecialchars($row['symbol']) ?></strong>
							</a>
						</td>
						<td class="performance-cell" data-symbol="<?= htmlspecialchars($row['symbol']) ?>" data-added="<?= htmlspecialchars($row['added_at']) ?>">
							Lädt …
						</td>
						<td>
							<?= htmlspecialchars($row['categories']) ?>
						</td>
						<td style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="<?= htmlspecialchars($row['note'] ?? '') ?>">
							<?php if (!empty($row['note'])): ?>
								<?= htmlspecialchars($row['note']) ?>
							<?php endif; ?>
						</td>
						<td>
							<?php
							$decoded = json_decode($row['rating_criteria'] ?? '[]', true);
							$score = is_array($decoded) ? count($decoded) : 0;
							
							$percent = $maxScore > 0 ? ($score / $maxScore) * 100 : 0;
							$scoreClass = $percent >= 75 ? 'success text-white'
										 : ($percent >= 25 ? 'secondary text-white'
										 : 'light text-dark');
							?>
							<span class="badge bg-<?= $scoreClass ?>">
								<i class="fa fa-star fa-sm"></i> <?= $score ?>/<?= $maxScore ?>
							</span>
						</td>
						<td>
							<div class="dropdown">
								<button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
									Aktion
								</button>
								<ul class="dropdown-menu dropdown-menu-end">
									<li>
										<a href="#" class="dropdown-item open-rating" data-symbol="<?= htmlspecialchars($row['symbol']) ?>">
											Bearbeiten
										</a>
									</li>
									<li>
										<a href="#" class="dropdown-item delete-btn text-danger">
											Löschen
										</a>
									</li>
									<li><hr class="dropdown-divider"></li>
									<li>
										<a href="/aktienbewertung.php?symbol=<?= htmlspecialchars($entry['symbol']) ?>" class="dropdown-item">
											Analysieren
										</a>
									</li>
								</ul>
							</div>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
	</div>
</main>

<div class="offcanvas offcanvas-end" tabindex="-1" id="ratingCanvas" aria-labelledby="ratingCanvasLabel">
	<div class="offcanvas-header border-bottom">
		<h3 class="fw-bold mb-0" id="ratingCanvasLabel"><span id="canvasSymbol"></span></h3>
		<button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
	</div>
	<div class="offcanvas-body">
		<h5><strong>Score: <span id="ratingScore">0/0</span></strong></h5>
		<div class="mb-2 small text-muted" id="canvasPrice">–</div>
		<canvas id="canvasChart" height="80" class="mb-3"></canvas>
		<form id="ratingForm">
			<div id="criteriaList" class="mb-4"></div>
			<div class="mb-3">
			  <label for="canvasNote" class="form-label">Notiz</label>
			  <input type="text" id="canvasNote" class="form-control" placeholder="Kommentar speichern …">
			</div>
			<button type="submit" class="btn btn-dark w-100 mt-2">Speichern</button>
		</form>
	</div>
</div>

<script>
	const criteria = <?= json_encode($ratingCriteria, JSON_UNESCAPED_UNICODE) ?>;
	
	document.querySelectorAll('.open-rating').forEach(btn => {
		btn.addEventListener('click', async function () {
			const symbol = this.dataset.symbol;
			document.getElementById('canvasSymbol').textContent = symbol;
	
			document.getElementById('canvasPrice').textContent = 'Lade Kurs …';
			const ctx = document.getElementById('canvasChart').getContext('2d');
			if (window.ratingChart) {
				window.ratingChart.destroy();
			}
	
			// Lade Kurs + Chart
			fetch(`/execute/watchlist/watchlist_stock-data.php?symbol=${symbol}`)
				.then(res => res.json())
				.then(data => {
					const changeClass = data.change_percent >= 0 ? 'text-success' : 'text-danger';
					document.getElementById('canvasPrice').innerHTML = `
						Aktueller Kurs: <strong>${data.price.toFixed(2)} $</strong><br>
						<span class="${changeClass}">${data.change.toFixed(2)} $ (${data.change_percent.toFixed(2)}%)</span>
					`;
	
					window.ratingChart = new Chart(ctx, {
						type: 'line',
						data: {
							labels: data.labels,
							datasets: [{
								data: data.values,
								borderColor: '#000',
								tension: 0.3,
								borderWidth: 1,
								pointRadius: 0
							}]
						},
						options: {
							responsive: true,
							plugins: { legend: { display: false } },
							scales: { x: { display: false }, y: { display: false } }
						}
					});
				});
	
			// Lade Bewertungskriterien
			const list = document.getElementById('criteriaList');
			list.innerHTML = '';
	
			const saved = await fetch(`/execute/watchlist/watchlist_get_rating.php?symbol=${symbol}`)
				.then(r => r.json())
				.catch(() => []);
	
			criteria.forEach((text, i) => {
				const checked = saved.includes(i.toString()) ? 'checked' : '';
				list.innerHTML += `
					<div class="form-check">
						<input class="form-check-input rating-check" type="checkbox" value="${i}" id="crit${i}" ${checked}>
						<label class="form-check-label" for="crit${i}">${text}</label>
					</div>
					<hr class="my-2">`;
			});
	
			// Lade Notiz
			const note = await fetch(`/execute/watchlist/watchlist_get_note.php?symbol=${symbol}`)
				.then(r => r.text())
				.catch(() => '');
			document.getElementById('canvasNote').value = note;
	
			updateScore();
			new bootstrap.Offcanvas(document.getElementById('ratingCanvas')).show();
		});
	});
	
	document.addEventListener('change', function (e) {
	  if (e.target.classList.contains('rating-check')) updateScore();
	});
	
	function updateScore() {
	  const total = document.querySelectorAll('.rating-check').length;
	  const checked = document.querySelectorAll('.rating-check:checked').length;
	  document.getElementById('ratingScore').textContent = `${checked}/${total}`;
	}
	
	document.getElementById('ratingForm').addEventListener('submit', async function (e) {
	  e.preventDefault();
	  const symbol = document.getElementById('canvasSymbol').textContent;
	  const checked = Array.from(document.querySelectorAll('.rating-check:checked')).map(cb => cb.value);
	
	  const formData = new FormData();
	  formData.append('symbol', symbol);
	  formData.append('checked', JSON.stringify(checked));
	  formData.append('note', document.getElementById('canvasNote').value);
	
	  const res = await fetch('/execute/watchlist/watchlist_save_rating.php', {
		method: 'POST',
		body: formData
	  });
	
	  if (res.ok) {
		bootstrap.Offcanvas.getInstance(document.getElementById('ratingCanvas')).hide();
	  } else {
		alert('Fehler beim Speichern.');
	  }
	});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
	const table = new DataTable('#watchlistTable', {
		order: [[1, 'asc']],
		pageLength: 50,
		lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "Alle"]],
		language: {
			url: "assets/js/data-tables_de-DE.json"
		},
		columnDefs: [
			{ orderable: false, targets: [0, 4, 5, 6] }
		]
	});

	document.querySelectorAll('.delete-btn').forEach(button => {
		button.addEventListener('click', async function () {
			const row = this.closest('tr');
			const symbol = row.dataset.symbol;

			if (!confirm(`Wirklich ${symbol} komplett aus der Watchlist entfernen?`)) return;

			const formData = new FormData();
			formData.append('symbol', symbol);
			formData.append('watchlist_action', 'remove_all');

			const response = await fetch('/execute/watchlist/watchlist_handler.php', {
				method: 'POST',
				headers: { 'X-Requested-With': 'XMLHttpRequest' },
				body: formData
			});

			if (response.ok) {
				table.row(row).remove().draw();
			} else {
				alert('Fehler beim Entfernen.');
			}
		});
	});
	
	document.querySelectorAll('.note-input').forEach(input => {
		input.addEventListener('blur', async function () {
			const symbol = this.dataset.symbol;
			const note = this.value;
	
			const formData = new FormData();
			formData.append('symbol', symbol);
			formData.append('update_note', '1');
			formData.append('note', note);
	
			const response = await fetch('/execute/watchlist/watchlist_handler.php', {
				method: 'POST',
				headers: { 'X-Requested-With': 'XMLHttpRequest' },
				body: formData
			});
	
			if (!response.ok) {
				alert('Fehler beim Speichern der Notiz.');
			}
		});
	});

	document.querySelectorAll('.toggle-mark').forEach(icon => {
		icon.addEventListener('click', async function () {
			const symbol = this.dataset.symbol;
			const isMarked = this.dataset.marked === '1';

			const formData = new FormData();
			formData.append('symbol', symbol);
			formData.append('toggle_mark', '1');
			formData.append('new_state', isMarked ? '0' : '1');

			const response = await fetch('/execute/watchlist/watchlist_handler.php', {
				method: 'POST',
				headers: { 'X-Requested-With': 'XMLHttpRequest' },
				body: formData
			});

			if (response.ok) {
				this.dataset.marked = isMarked ? '0' : '1';
				this.classList.toggle('text-secondary');
				this.classList.toggle('text-danger');
			} else {
				alert('Fehler beim Markieren');
			}
		});
	});
	
	document.querySelectorAll('.performance-cell').forEach(async cell => {
		const symbol = cell.dataset.symbol;
		const addedAt = cell.dataset.added;
	
		try {
			const res = await fetch(`/execute/watchlist/watchlist_get_performance.php?symbol=${symbol}&added_at=${addedAt}`);
			const data = await res.json();
	
			if (data.performance === null) {
				cell.innerHTML = '<span class="text-muted">–</span>';
				return;
			}
	
			const cls = data.performance >= 0 ? 'text-success' : 'text-danger';
	
			cell.innerHTML = `
				<small class="${cls}">
					${data.performance.toFixed(2)} %
				</small>
				<small class="text-muted d-block">seit ${data.start_date}</small>
			`;
		} catch (err) {
			cell.innerHTML = '<span class="text-muted">Fehler</span>';
		}
	});

});
</script>

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