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

try {
	// Eingaben
	$id   = isset($_POST['id']) ? (int)$_POST['id'] : 0;
	$type = isset($_POST['type']) ? trim((string)$_POST['type']) : '';
	$amount = isset($_POST['amount']) ? (float)$_POST['amount'] : null;
	$date = isset($_POST['date']) ? trim((string)$_POST['date']) : '';
	$note = isset($_POST['note']) ? trim((string)$_POST['note']) : '';

	// Multi-Depot optional
	$portfolioId = isset($_POST['portfolio_id']) ? (int)$_POST['portfolio_id']
				 : (isset($_POST['pid']) ? (int)$_POST['pid'] : null);

	// Validierung
	if ($id <= 0 || $amount === null || $amount < 0 || $date === '' || !in_array($type, ['deposit','withdraw'], true)) {
		http_response_code(400);
		echo json_encode(['success'=>false, 'error'=>'Ungültige Eingabe.']);
		exit;
	}

	// Prüfen, ob Spalte portfolio_id in depot_cash existiert (sanft)
	$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;
	}

	// Update
	$sql = "UPDATE depot_cash
			SET type = :type,
				amount = :amount,
				flow_date = :flow_date,
				note = :note
			WHERE id = :id";
	$params = [
		':type'      => $type,
		':amount'    => $amount,
		':flow_date' => $date,
		':note'      => $note,
		':id'        => $id,
	];

	// Falls portfolio_id verwendet wird: zusätzlich absichern
	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()]);
}