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

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  echo json_encode(['success' => false, 'error' => 'Invalid method']); exit;
}

$id = (int)($_POST['portfolio_id'] ?? 0);
if ($id <= 0) { echo json_encode(['success' => false, 'error' => 'Fehlende ID']); exit; }

try {
  $pdo->beginTransaction();
  // Delete related data
  $pdo->prepare("DELETE FROM depot_entries WHERE portfolio_id = :id")->execute([':id' => $id]);
  $pdo->prepare("DELETE FROM depot_cash WHERE portfolio_id = :id")->execute([':id' => $id]);
  $pdo->prepare("DELETE FROM depot_meta WHERE portfolio_id = :id")->execute([':id' => $id]);
  // Finally delete portfolio row
  $pdo->prepare("DELETE FROM depot_portfolios WHERE id = :id")->execute([':id' => $id]);
  $pdo->commit();
  echo json_encode(['success' => true]);
} catch (Throwable $e) {
  if ($pdo->inTransaction()) { $pdo->rollBack(); }
  http_response_code(500);
  echo json_encode(['success' => false, 'error' => 'DB-Fehler: '.$e->getMessage()]);
}
