<?php
require_once '../../engine/engine.php';

if (isset($_POST['toggle_mark']) && isset($_POST['symbol']) && isset($_POST['new_state'])) {
	$symbol = $_POST['symbol'];
	$newState = (int)$_POST['new_state'];

	$stmt = $pdo->prepare("UPDATE watchlist SET is_marked = ? WHERE symbol = ?");
	$stmt->execute([$newState, $symbol]);

	http_response_code(200);
	echo 'updated';
	exit;
}

if (isset($_POST['update_note']) && isset($_POST['symbol'])) {
	$symbol = $_POST['symbol'];
	$note = trim($_POST['note'] ?? '');

	$stmt = $pdo->prepare("UPDATE watchlist SET note = ? WHERE symbol = ?");
	$stmt->execute([$note, $symbol]);

	http_response_code(200);
	echo 'note updated';
	exit;
}

$symbol = $_POST['symbol'] ?? null;
$category = $_POST['category'] ?? null;
$action = $_POST['watchlist_action'] ?? null;

if ($action === 'remove_all' && $symbol) {
	$stmt = $pdo->prepare("DELETE FROM watchlist WHERE symbol = ?");
	$stmt->execute([$symbol]);
	http_response_code(200);
	echo 'removed all';
	exit;
}

if (!$symbol || !$category || !$action) {
	http_response_code(400);
	echo 'Fehlende Daten';
	exit;
}

$symbol = strtoupper($symbol);

try {
	if ($action === 'add') {
		$stmt = $pdo->prepare("INSERT IGNORE INTO watchlist (symbol, category) VALUES (?, ?)");
		$stmt->execute([$symbol, $category]);
		http_response_code(200);
		echo 'added';
	} elseif ($action === 'remove') {
		$stmt = $pdo->prepare("DELETE FROM watchlist WHERE symbol = ? AND category = ?");
		$stmt->execute([$symbol, $category]);
		http_response_code(200);
		echo 'removed';
	} else {
		http_response_code(400);
		echo 'Ungültige Aktion';
	}
} catch (Exception $e) {
	http_response_code(500);
	echo 'Fehler: ' . $e->getMessage();
}