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

try {
  // Formularfeld heißt start_capital
  $capital = isset($_POST['start_capital']) ? (float)$_POST['start_capital'] 
   : (isset($_POST['capital']) ? (float)$_POST['capital'] : null);

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

  if ($capital === null) {
    throw new Exception('Kein Kapitalwert übergeben.');
  }

  // WICHTIG: In depot_meta muss ein UNIQUE(meta_key, portfolio_id) existieren!
  // ALTER TABLE depot_meta ADD UNIQUE KEY uniq_meta_portfolio (meta_key, portfolio_id);

  $stmt = $pdo->prepare("
    INSERT INTO depot_meta (meta_key, meta_value, portfolio_id)
    VALUES ('start_capital', :val, :pid)
    ON DUPLICATE KEY UPDATE meta_value = VALUES(meta_value)
  ");
  $stmt->execute([
    ':val' => $capital,
    ':pid' => $portfolioId
  ]);

  echo json_encode(['success' => true, 'ok' => true], JSON_UNESCAPED_UNICODE);

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