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

// Eingabewerte holen
$id        = isset($_POST['id']) ? (int)$_POST['id'] : null;
$sell_price = isset($_POST['sell_price']) ? (float)$_POST['sell_price'] : null;
$sell_date  = $_POST['sell_date'] ?? '';
$sell_fees  = isset($_POST['sell_fees']) ? (float)$_POST['sell_fees'] : 0.0;

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

// Validierung
if (!$id || $sell_price === null || !$sell_date) {
	http_response_code(400);
	echo "Ungültige Eingabe.";
	exit;
}

// Prüfen, ob depot_entries.portfolio_id existiert
$hasPid = false;
try {
	$chk = $pdo->prepare("SHOW COLUMNS FROM `depot_entries` LIKE 'portfolio_id'");
	$chk->execute();
	$hasPid = (bool)$chk->fetchColumn();
} catch (Throwable $e) {
	$hasPid = false;
}

// SQL-Basis
$sql = "
	UPDATE depot_entries
	SET status = 'sold',
		sell_price = :sell_price,
		sell_date  = :sell_date,
		sell_fees  = :sell_fees
";
$params = [
	':sell_price' => $sell_price,
	':sell_date'  => $sell_date,
	':sell_fees'  => $sell_fees,
	':id'         => $id
];

// Falls portfolio_id-Spalte vorhanden und Wert gesetzt → übernehmen
if ($hasPid && $portfolioId !== null) {
	$sql .= ", portfolio_id = :pid";
	$params[':pid'] = $portfolioId;
}

$sql .= " WHERE id = :id";

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

echo 'success';