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

try {
	// Eingaben normalisieren (wir akzeptieren shares aus 'shares' und 'sell_shares')
	$id           = isset($_POST['id']) ? (int)$_POST['id'] : 0;
	$sharesInput1 = isset($_POST['shares']) ? $_POST['shares'] : null;
	$sharesInput2 = isset($_POST['sell_shares']) ? $_POST['sell_shares'] : null;
	$shares       = (float)($sharesInput2 !== null ? $sharesInput2 : ($sharesInput1 !== null ? $sharesInput1 : 0));

	$price      = isset($_POST['price']) ? (float)$_POST['price'] : null;              // neuer Verkauf (active)
	$sell_price = isset($_POST['sell_price']) ? (float)$_POST['sell_price'] : null;   // bearbeiten (sold)

	$date       = isset($_POST['date']) ? trim($_POST['date']) : null;                 // neuer Verkauf
	$sell_date  = isset($_POST['sell_date']) ? trim($_POST['sell_date']) : null;       // bearbeiten

	$fees       = isset($_POST['fees']) && $_POST['fees'] !== '' ? (float)$_POST['fees'] : 0.0;           // neuer Verkauf
	$sell_fees  = isset($_POST['sell_fees']) && $_POST['sell_fees'] !== '' ? (float)$_POST['sell_fees'] : null; // bearbeiten

	$notes      = isset($_POST['notes']) ? trim($_POST['notes']) : null;

	// Multi-Depot
	$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.');
	}

	// Eintrag laden (nur innerhalb des aktuellen Depots)
	$stmt = $pdo->prepare("SELECT * FROM depot_entries WHERE id = :id AND portfolio_id = :pid LIMIT 1");
	$stmt->execute([':id' => $id, ':pid' => $portfolioId]);
	$entry = $stmt->fetch(PDO::FETCH_ASSOC);
	if (!$entry) {
		throw new Exception('Eintrag nicht gefunden (Depot).');
	}

	$status = $entry['status'];

	$pdo->beginTransaction();

	if ($status === 'active') {
		// Neuer Verkauf einer aktiven Position
		if ($price === null || !$date) {
			throw new Exception('Preis und Datum sind für den Verkauf erforderlich.');
		}
		if ($shares <= 0) {
			throw new Exception('Verkaufte Stückzahl muss > 0 sein.');
		}

		$availShares = (float)$entry['shares'];
		if ($shares > $availShares + 1e-9) {
			throw new Exception('Verkaufte Stückzahl überschreitet verfügbare Stücke.');
		}

		// Vollverkauf -> vorhandene Zeile auf "sold" setzen
		if (abs($shares - $availShares) < 1e-9) {
			$upd = $pdo->prepare("
				UPDATE depot_entries
				SET status = 'sold',
					sell_price = :sp,
					sell_date  = :sd,
					sell_fees  = :sf,
					notes      = CASE WHEN :notes IS NULL OR :notes = '' THEN notes ELSE :notes END
				WHERE id = :id
				  AND portfolio_id = :pid
				  AND status = 'active'
			");
			$upd->execute([
				':sp'    => $price,
				':sd'    => $date,
				':sf'    => $fees,
				':notes' => $notes,
				':id'    => $id,
				':pid'   => $portfolioId
			]);

			if ($upd->rowCount() === 0) {
				throw new Exception('Verkauf fehlgeschlagen (Vollverkauf).');
			}
		} else {
			// Teilverkauf -> aktive Zeile reduzieren & separate sold-Zeile anlegen
			$newActiveShares = $availShares - $shares;

			$updActive = $pdo->prepare("
				UPDATE depot_entries
				SET shares = :new_shares
				WHERE id = :id
				  AND portfolio_id = :pid
				  AND status = 'active'
			");
			$updActive->execute([
				':new_shares' => $newActiveShares,
				':id'         => $id,
				':pid'        => $portfolioId
			]);
			if ($updActive->rowCount() === 0) {
				throw new Exception('Update der aktiven Position fehlgeschlagen.');
			}

			// neue sold-Zeile (Lot) anlegen – gleiche Stammdaten, aber shares=verkaufter Anteil
			$insSold = $pdo->prepare("
				INSERT INTO depot_entries
				(symbol, exchange, isin, strategy, shares, buy_price, stop_price, take_profit_price, buy_date,
				 fees, notes, image, status, sell_price, sell_date, sell_fees, portfolio_id, created_at)
				VALUES
				(:symbol, :exchange, :isin, :strategy, :shares, :buy_price, :stop_price, :take_profit_price, :buy_date,
				 :fees, :notes, :image, 'sold', :sell_price, :sell_date, :sell_fees, :pid, NOW())
			");
			$insSold->execute([
				':symbol'            => $entry['symbol'],
				':exchange'          => $entry['exchange'],
				':isin'              => $entry['isin'],
				':strategy'          => $entry['strategy'],
				':shares'            => $shares,
				':buy_price'         => $entry['buy_price'],
				':stop_price'        => $entry['stop_price'],
				':take_profit_price' => $entry['take_profit_price'],
				':buy_date'          => $entry['buy_date'],
				':fees'              => $entry['fees'], // ursprüngliche Kaufspesen
				':notes'             => ($notes !== null && $notes !== '') ? $notes : $entry['notes'],
				':image'             => $entry['image'],
				':sell_price'        => $price,
				':sell_date'         => $date,
				':sell_fees'         => $fees,
				':pid'               => $portfolioId
			]);
		}
	} elseif ($status === 'sold') {
		// Bearbeiten eines bereits verkauften Eintrags
		// shares können geändert werden (z. B. Korrektur), ebenso sell_price, sell_fees, sell_date, notes
		$newShares   = ($shares > 0) ? $shares : (float)$entry['shares'];
		$newPrice    = ($sell_price !== null) ? $sell_price : (float)$entry['sell_price'];
		$newFees     = ($sell_fees !== null) ? $sell_fees : (float)$entry['sell_fees'];
		$newDate     = ($sell_date !== null && $sell_date !== '') ? $sell_date : $entry['sell_date'];
		$newNotes    = ($notes !== null && $notes !== '') ? $notes : $entry['notes'];

		$updSold = $pdo->prepare("
			UPDATE depot_entries
			SET shares = :shares,
				sell_price = :sp,
				sell_fees  = :sf,
				sell_date  = :sd,
				notes      = :notes
			WHERE id = :id
			  AND portfolio_id = :pid
			  AND status = 'sold'
		");
		$updSold->execute([
			':shares' => $newShares,
			':sp'     => $newPrice,
			':sf'     => $newFees,
			':sd'     => $newDate,
			':notes'  => $newNotes,
			':id'     => $id,
			':pid'    => $portfolioId
		]);

		if ($updSold->rowCount() === 0) {
			throw new Exception('Update des Verkaufseintrags fehlgeschlagen.');
		}
	} else {
		throw new Exception('Unbekannter Status.');
	}

	$pdo->commit();
	echo json_encode(['success' => true], JSON_UNESCAPED_UNICODE);

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