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

header('Content-Type: application/json; charset=utf-8');

$symbol = isset($_GET['symbol']) ? trim($_GET['symbol']) : '';
$pid = isset($_GET['portfolio_id']) ? (int)$_GET['portfolio_id']
      : (isset($_GET['pid']) ? (int)$_GET['pid'] : 1);

// NEU: Check nur erzwingen, wenn enforce=1 (Standard: 0)
$enforce = isset($_GET['enforce']) ? (int)$_GET['enforce'] : 0;

if ($symbol === '') {
  http_response_code(400);
  echo json_encode(['error' => 'symbol required']);
  exit;
}

try {
  if ($enforce === 1) {
    $stmt = $pdo->prepare("
      SELECT COUNT(*) 
      FROM depot_entries
      WHERE symbol = :symbol AND portfolio_id = :pid
    ");
    $stmt->execute([':symbol' => $symbol, ':pid' => $pid]);
    if ($stmt->fetchColumn() == 0) {
      http_response_code(403);
      echo json_encode(['error' => 'symbol not in portfolio']);
      exit;
    }
  }

  // --- Quote via fmp_multi (nur Logik getauscht) ---
  if (empty($symbol)) {
      throw new \RuntimeException('Symbol fehlt.');
  }
  $symbol = strtoupper(trim($symbol));
  
  // 1) Request bauen und abfeuern
  $resp = fmp_multi([
      'q' => ['key' => 'quote', 'vars' => ['symbol' => $symbol]],
      // alternativ: 'quote_short', wenn ihr bewusst die kurze Variante wollt
  ], 4);
  
  // 2) Robust entpacken (Array[0] / Wrapper / JSON-String)
  $node = $resp['q'] ?? [];
  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) && isset($node['body'])) { $node = $node['body']; }
  if (is_array($node) && isset($node['data'])) { $node = $node['data']; }
  if (is_array($node) && array_key_exists(0, $node) && is_array($node[0])) {
      $node = $node[0]; // /api/v3/quote liefert meist [0]
  }
  
  // 3) In gewohntes Quote-Array mappen
  $quote = [
      'symbol'    => $node['symbol']   ?? $symbol,
      'price'     => isset($node['price']) ? (float)$node['price'] : null,
      'currency'  => $node['currency'] ?? ($node['Currency'] ?? null),
      'exchange'  => $node['exchange'] ?? ($node['Exchange'] ?? null),
      'timestamp' => $node['timestamp'] ?? ($node['latestUpdate'] ?? ($node['date'] ?? null)),
  ];
  $quote['date'] = $quote['timestamp'] ?? null;
  
  // --- Ende Quote via fmp_multi ---
  
  $data = $quote;
  
  if (!$data || !isset($data['price'])) {
      echo json_encode([
          'symbol' => $symbol,
          'price'  => null,
          'date'   => null
      ], JSON_UNESCAPED_UNICODE);
      exit;
  }
  
  echo json_encode([
    'symbol' => $symbol,
    'price'  => (float)$data['price'],
    'date'   => $data['date'] ?? null,   // kommt jetzt aus $quote['date']
  ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['error' => 'server error']);
}