<?php
require_once __DIR__ . '/../../engine/engine.php';
require_once __DIR__ . '/../../engine/api-handling/fmp_client.php';

// Eingabewerte holen
$id        = isset($_POST['id']) ? (int)$_POST['id'] : null;
$symbol    = isset($_POST['symbol']) ? strtoupper(trim($_POST['symbol'])) : '';
$assetKind = isset($_POST['asset_kind']) ? trim((string)$_POST['asset_kind']) : '';
$shares    = isset($_POST['shares']) ? (float)$_POST['shares'] : null;
$buy_price = isset($_POST['buy_price']) ? (float)$_POST['buy_price'] : null;
$buy_date  = isset($_POST['buy_date']) ? trim((string)$_POST['buy_date']) : '';
$fees      = isset($_POST['fees']) ? (float)$_POST['fees'] : 0.0;
$strategy  = isset($_POST['strategy']) ? trim((string)$_POST['strategy']) : '';

$stop_price = (isset($_POST['stop_price']) && $_POST['stop_price'] !== '') ? (float)$_POST['stop_price'] : null;
$take_profit_price = (isset($_POST['take_profit_price']) && $_POST['take_profit_price'] !== '') ? (float)$_POST['take_profit_price'] : null;

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

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

// Basis-Validierung
if (!$id || $symbol === '' || !$shares || !$buy_price || $buy_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;
}

/**
 * 1) Wenn Symbol gesetzt ist, Profil laden (exchange/isin/image)
 *    - Sanft fehlertolerant, damit ein API-Issue das Update nicht verhindert.
 */
// Vorab defensiv initialisieren (verhindert Notices, falls Catch greift)
 $exchange = $exchange ?? null;
 $isin     = $isin     ?? null;
 $image    = $image    ?? null;
 
 try {
	 if (empty($symbol)) {
		 throw new \RuntimeException('Symbol fehlt.');
	 }
 
	 $symbol = strtoupper(trim($symbol));
 
	 // Profile + (optional) Quote via fmp_multi
	 $resp = fmp_multi([
		 'profile' => ['key' => 'profile', 'vars' => ['symbol' => $symbol]],
		 'quote'   => ['key' => 'quote',   'vars' => ['symbol' => $symbol]],
	 ], 8);
 
	 // Entpack-Helfer (String/stdClass/Wrapper → Assoc; Array[0] abfangen)
	 $unwrap = static function ($node) {
		 if (is_string($node)) {
			 $tmp = json_decode($node, true);
			 if (json_last_error() === JSON_ERROR_NONE) { $node = $tmp; }
		 }
		 if (is_object($node)) { $node = json_decode(json_encode($node), true); }
		 if (!is_array($node) || !$node) { return []; }
		 foreach (['body','data','result','json','payload','response'] as $k) {
			 if (array_key_exists($k, $node)) { $node = $node[$k]; break; }
		 }
		 if (is_array($node) && array_key_exists(0, $node) && is_array($node[0])) {
			 return $node[0];
		 }
		 return $node;
	 };
 
	 $prof  = $unwrap($resp['profile'] ?? null);
	 $quote = $unwrap($resp['quote']   ?? null);
 
	 // Feldmapping mit gängigen Fallbacks
	 $exchange = $prof['exchangeShortName']
		 ?? $prof['exchange']
		 ?? $quote['exchange']
		 ?? $exchange;
 
	 $isin = $prof['isin']
		 ?? $prof['ISIN']
		 ?? $isin;
 
	 $image = $prof['image']
		 ?? $prof['profileImage']
		 ?? $prof['imageUrl']
		 ?? $prof['logo']
		 ?? $image;
 
	 // (optional) säubern
	 if (is_string($exchange)) { $exchange = trim($exchange); }
	 if (is_string($isin))     { $isin     = trim($isin);     }
	 if (is_string($image))    { $image    = trim($image);    }
 
 } catch (\Throwable $ex) {
	 error_log('[depot_update_entry] FMP Fetch Error: ' . $ex->getMessage());
	 // $exchange/$isin/$image bleiben auf ihren bisherigen (ggf. null) Werten
 }

/**
 * 2) Update-Query: Symbol & Felder + (falls vorhanden) exchange/isin/image mitschreiben.
 *    Wichtig: portfolio_id nur in WHERE absichern, NICHT ändern.
 */
$sql = "
  UPDATE depot_entries
  SET symbol = :symbol,
	  strategy = :strategy,
	  asset_kind = :asset_kind,
	  shares = :shares,
	  buy_price = :buy_price,
	  stop_price = :stop_price,
	  take_profit_price = :take_profit_price,
	  buy_date = :buy_date,
	  fees = :fees,
	  notes = :notes
";

$params = [
	':symbol'            => $symbol,
	':strategy'          => $strategy,
	':asset_kind'        => $assetKind,
	':shares'            => $shares,
	':buy_price'         => $buy_price,
	':stop_price'        => $stop_price,
	':take_profit_price' => $take_profit_price,
	':buy_date'          => $buy_date,
	':fees'              => $fees,
	':notes'             => $notes,
	':id'                => $id,
];

// exchange/isin/image nur setzen, wenn wir Werte haben (kein Überschreiben mit NULL)
if ($exchange !== null) { $sql .= ", exchange = :exchange"; $params[':exchange'] = $exchange; }
if ($isin     !== null) { $sql .= ", isin = :isin";         $params[':isin']     = $isin; }
if ($image    !== null) { $sql .= ", image = :image";       $params[':image']    = $image; }

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

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

echo 'success';