<?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'] : 1);

	if ($id <= 0) throw new Exception('Ungültige ID.');

	// Verkauften Eintrag im aktuellen Depot suchen
	$stmt = $pdo->prepare("
		SELECT * FROM depot_entries 
		WHERE id = :id AND status = 'sold' AND portfolio_id = :pid
	");
	$stmt->execute([':id' => $id, ':pid' => $portfolioId]);
	$sold = $stmt->fetch(PDO::FETCH_ASSOC);
	if (!$sold) throw new Exception('Verkaufseintrag nicht gefunden.');

	$shares    = (float)$sold['shares'];
	$sellPrice = (float)$sold['sell_price'];
	$sellFees  = isset($sold['sell_fees']) ? (float)$sold['sell_fees'] : 0.0;
	$proceeds  = $shares * $sellPrice - $sellFees;

	$pdo->beginTransaction();

	// Aktuellen Cash-Bestand für das Depot holen
	$currentCash = (float)($pdo->prepare("
		SELECT amount FROM depot_cash 
		WHERE portfolio_id = :pid 
		ORDER BY id DESC LIMIT 1
	")->execute([':pid' => $portfolioId]) 
		? $pdo->prepare("SELECT amount FROM depot_cash WHERE portfolio_id = :pid ORDER BY id DESC LIMIT 1")->execute([':pid' => $portfolioId]) 
		: 0.0
	);

	$newCash = $currentCash - $proceeds;

	$insCash = $pdo->prepare("
		INSERT INTO depot_cash (amount, portfolio_id) VALUES (:amount, :pid)
	");
	$insCash->execute([':amount' => $newCash, ':pid' => $portfolioId]);

	// Passenden aktiven Eintrag im gleichen Depot suchen
	$match = $pdo->prepare("
		SELECT id FROM depot_entries
		WHERE status='active' 
		  AND symbol=:symbol 
		  AND buy_price=:bp 
		  AND buy_date=:bd 
		  AND (strategy <=> :strategy)
		  AND portfolio_id = :pid
		ORDER BY id DESC LIMIT 1
	");
	$match->execute([
		':symbol'   => $sold['symbol'],
		':bp'       => $sold['buy_price'],
		':bd'       => $sold['buy_date'],
		':strategy' => $sold['strategy'],
		':pid'      => $portfolioId
	]);
	$active = $match->fetch(PDO::FETCH_ASSOC);

	if ($active) {
		$upd = $pdo->prepare("
			UPDATE depot_entries 
			SET shares = shares + :s 
			WHERE id = :id AND portfolio_id = :pid
		");
		$upd->execute([':s' => $shares, ':id' => $active['id'], ':pid' => $portfolioId]);

		$del = $pdo->prepare("
			DELETE FROM depot_entries 
			WHERE id = :id AND status='sold' AND portfolio_id = :pid
		");
		$del->execute([':id' => $id, ':pid' => $portfolioId]);
	} else {
		$react = $pdo->prepare("
			UPDATE depot_entries
			SET status='active', sell_price=NULL, sell_date=NULL, sell_fees=NULL
			WHERE id = :id AND status='sold' AND portfolio_id = :pid
		");
		$react->execute([':id' => $id, ':pid' => $portfolioId]);
	}

	$pdo->commit();
	echo json_encode(['success' => true, 'cash' => round($newCash, 2)]);
} catch (Exception $e) {
	if ($pdo->inTransaction()) $pdo->rollBack();
	http_response_code(400);
	echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
