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

try {
	$data = $_POST;

	// ---- 1) Pflichtfelder prüfen ----
	$required = ['symbol', 'shares', 'buy_price', 'buy_date'];
	foreach ($required as $field) {
		if (!isset($data[$field]) || $data[$field] === '') {
			http_response_code(400);
			echo "Feld '$field' ist erforderlich.";
			exit;
		}
	}

	// ---- 2) Portfolio-ID (neu) einlesen & validieren ----
	$portfolioId = isset($data['portfolio_id']) ? (int)$data['portfolio_id'] : (isset($data['pid']) ? (int)$data['pid'] : 1);

	// Wenn Spalte/Feature noch nicht überall vorhanden ist, kannst du das Try-Catch als Soft-Fallback nutzen:
	$portfolioExists = true;
	try {
		$stmtCheck = $pdo->prepare("SELECT 1 FROM depot_portfolios WHERE id = :id LIMIT 1");
		$stmtCheck->execute([':id' => $portfolioId]);
		$portfolioExists = (bool)$stmtCheck->fetchColumn();
	} catch (Throwable $e) {
		// Wenn Tabelle (noch) nicht existiert, defaulten wir auf 1
		$portfolioExists = false;
	}
	if (!$portfolioExists) {
		http_response_code(400);
		echo "Ungültige portfolio_id.";
		exit;
	}

	// ---- 3) Felder aufbereiten (dein Stil, defensiv gecastet) ----
	$symbol   = strtoupper(trim($data['symbol']));
	$strategy = trim($data['strategy'] ?? '');
	$assetKind  = trim($data['asset_kind'] ?? '');
	$shares   = (float)$data['shares'];
	$buyPrice = (float)$data['buy_price'];
	$stopPrice = isset($data['stop_price']) && $data['stop_price'] !== '' ? (float)$data['stop_price'] : null;
	$tpPrice   = isset($data['take_profit_price']) && $data['take_profit_price'] !== '' ? (float)$data['take_profit_price'] : null;
	$buyDate  = trim($data['buy_date']);
	$fees     = isset($data['fees']) && $data['fees'] !== '' ? (float)$data['fees'] : 0.0;
	$notes    = trim($data['notes'] ?? '');

	// ---- 4) Basisinfos zum Symbol laden (wie bei dir: exchange/isin/image etc.) ----
	// Vor dem try optional sicher initialisieren (verhindert Notices bei Catch)
	$exchange = $exchange ?? null;
	$isin     = $isin     ?? null;
	$image    = $image    ?? null;
	
	try {
		if (empty($symbol)) {
			throw new \RuntimeException('Symbol fehlt.');
		}
	
		$symbol = strtoupper(trim($symbol));
	
		// 1) FMP holen
		$resp = fmp_multi([
			'profile' => ['key' => 'profile', 'vars' => ['symbol' => $symbol]],
			'quote'   => ['key' => 'quote',   'vars' => ['symbol' => $symbol]],
		], 8);
	
		// kleine Hilfsfunktion zum Entpacken verschiedenster Formate
		$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)) {
					// einmalig weiter entpacken
					$node = $node[$k];
					break;
				}
			}
			// numerisches Array? -> erstes Element
			if (array_key_exists(0, $node) && is_array($node[0])) {
				return $node[0];
			}
			return $node; // bereits assoc
		};
	
		// 2) Unwrap Profile & Quote
		$prof  = $unwrap($resp['profile'] ?? null);
		$quote = $unwrap($resp['quote']   ?? null);
	
		// 3) Robustes Mapping (mit gängigen Alternativfeldern)
		$exchange = $prof['exchangeShortName']
			?? $prof['exchange']
			?? $quote['exchange']
			?? null;
	
		$isin = $prof['isin']
			?? $prof['ISIN']
			?? null;
	
		$image = $prof['image']
			?? $prof['profileImage']
			?? $prof['imageUrl']
			?? $prof['logo']           // falls Registry/Client so nennt
			?? null;
	
		// (optional) sanitisieren
		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_add_entry] FMP Fetch Error: ' . $ex->getMessage());
		// Variablen bleiben auf null
	}
	
	// ---- 5) INSERT mit portfolio_id ----
	$sql = "
	  INSERT INTO depot_entries
	  (symbol, exchange, isin, strategy, asset_kind, shares, buy_price, stop_price, take_profit_price, buy_date, fees, notes, image, status, portfolio_id, created_at)
	  VALUES
	  (:symbol, :exchange, :isin, :strategy, :asset_kind, :shares, :buy_price, :stop_price, :take_profit_price, :buy_date, :fees, :notes, :image, 'active', :pid, NOW())
	";
	$stmt = $pdo->prepare($sql);
	$stmt->execute([
		':symbol'            => $symbol,
		':exchange'          => $exchange,
		':isin'              => $isin,
		':strategy'          => $strategy,
		':asset_kind'        => $assetKind,
		':shares'            => $shares,
		':buy_price'         => $buyPrice,
		':stop_price'        => $stopPrice,
		':take_profit_price' => $tpPrice,
		':buy_date'          => $buyDate,
		':fees'              => $fees,
		':notes'             => $notes,
		':image'             => $image,
		':pid'               => $portfolioId,
	]);

	echo 'success';
} catch (Throwable $e) {
	http_response_code(500);
	echo 'DB-Fehler: ' . $e->getMessage();
}