<?php
if (!isset($symbol) || !$symbol) {
	return;
}

$category = $category ?? 'Saisonalität';

$stmt = $pdo->prepare("SELECT COUNT(*) FROM watchlist WHERE symbol = ? AND category = ?");
$stmt->execute([strtoupper($symbol), $category]);
$isInWatchlist = $stmt->fetchColumn() > 0;
?>

<button id="watchlistButton"
	data-symbol="<?= htmlspecialchars($symbol) ?>"
	data-category="<?= htmlspecialchars($category ?? 'Saisonalität') ?>"
	data-action="<?= $isInWatchlist ? 'remove' : 'add' ?>"
	class="btn btn-outline-<?= $isInWatchlist ? 'danger' : 'success' ?>">
	<?= $isInWatchlist ? '− Watchlist' : '+ Watchlist' ?>
</button>

<script>
document.addEventListener('DOMContentLoaded', function () {
	const btn = document.getElementById('watchlistButton');
	const feedback = document.getElementById('watchlistFeedback');

	btn?.addEventListener('click', async function () {
		const symbol = btn.dataset.symbol;
		const category = btn.dataset.category;
		const action = btn.dataset.action;

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

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

		const result = await response.text();

		if (response.ok) {
			btn.dataset.action = (action === 'add') ? 'remove' : 'add';
			btn.classList.toggle('btn-outline-success');
			btn.classList.toggle('btn-outline-danger');
			btn.innerText = (action === 'add') ? '− Watchlist' : '+ Watchlist';
		}
	});
});

</script>
