<?php
require_once __DIR__ . '/../../engine/engine.php';
header('Content-Type: application/json; charset=utf-8');

try {
	$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
	$portfolioId = isset($_POST['portfolio_id']) ? (int)$_POST['portfolio_id']
				 : (isset($_POST['pid']) ? (int)$_POST['pid'] : null);

	if ($id <= 0) {
		http_response_code(400);
		echo json_encode(['success'=>false, 'error'=>'Ungültige ID.']);
		exit;
	}

	$hasPid = false;
	try {
		$chk = $pdo->prepare("SHOW COLUMNS FROM `depot_cash` LIKE 'portfolio_id'");
		$chk->execute();
		$hasPid = (bool)$chk->fetchColumn();
	} catch (Throwable $e) {
		$hasPid = false;
	}

	$sql = "DELETE FROM depot_cash WHERE id = :id";
	$params = [ ':id' => $id ];

	if ($hasPid && $portfolioId !== null) {
		$sql .= " AND portfolio_id = :pid";
		$params[':pid'] = $portfolioId;
	}

	$stmt = $pdo->prepare($sql);
	$stmt->execute($params);

	echo json_encode(['success'=>true]);
} catch (Throwable $e) {
	http_response_code(500);
	echo json_encode(['success'=>false, 'error'=>'DB-Fehler: '.$e->getMessage()]);
}