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

try {
  // --- Eingaben ---
  $amount = isset($_POST['amount']) ? (float)$_POST['amount'] : 0;
  $type   = $_POST['type'] ?? ''; // 'deposit' | 'withdraw'
  $date   = $_POST['date'] ?? date('Y-m-d');
  $note   = $_POST['note'] ?? null;

  // Multi-Depot: portfolio_id (kommt aus Hidden-Feld im Offcanvas)
  $portfolioId = isset($_POST['portfolio_id']) ? (int)$_POST['portfolio_id']
                : (isset($_POST['pid']) ? (int)$_POST['pid'] : 1);

  // --- Input prüfen ---
  if (!in_array($type, ['deposit','withdraw'], true) || $amount <= 0) {
    http_response_code(400);
    echo json_encode(['ok'=>false, 'msg'=>'Invalid input']); exit;
  }

  // --- Portfolio existiert? (sanfte Validierung) ---
  $portfolioExists = true;
  try {
    $chk = $pdo->prepare("SELECT 1 FROM depot_portfolios WHERE id = :id LIMIT 1");
    $chk->execute([':id' => $portfolioId]);
    $portfolioExists = (bool)$chk->fetchColumn();
  } catch (Throwable $e) {
    $portfolioExists = false;
  }
  if ($portfolioExists === false) {
    http_response_code(400);
    echo json_encode(['ok'=>false, 'msg'=>'Ungültige portfolio_id']); exit;
  }

  // --- Hilfsfunktion: Spalte vorhanden? ---
  $hasPid = false;
  try {
    $q = $pdo->prepare("SHOW COLUMNS FROM `depot_cash` LIKE 'portfolio_id'");
    $q->execute();
    $hasPid = (bool)$q->fetchColumn();
  } catch (Throwable $e) {
    $hasPid = false;
  }

  if ($hasPid) {
    $stmt = $pdo->prepare("
      INSERT INTO depot_cash (amount, flow_date, type, is_snapshot, created_at, last_updated, note, portfolio_id)
      VALUES (:amount, :flow_date, :type, 0, NOW(), NOW(), :note, :pid)
    ");
    $stmt->execute([
      ':amount'    => $amount,
      ':flow_date' => $date,
      ':type'      => $type,
      ':note'      => $note,
      ':pid'       => $portfolioId,
    ]);
  } else {
    $stmt = $pdo->prepare("
      INSERT INTO depot_cash (amount, flow_date, type, is_snapshot, created_at, last_updated, note)
      VALUES (:amount, :flow_date, :type, 0, NOW(), NOW(), :note)
    ");
    $stmt->execute([
      ':amount'    => $amount,
      ':flow_date' => $date,
      ':type'      => $type,
      ':note'      => $note,
    ]);
  }

  echo json_encode(['ok'=>true]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['ok'=>false, 'msg'=>'DB-Fehler: '.$e->getMessage()]);
}