<?php
require_once __DIR__ . '/engine/engine.php';
$requires_search = true;
$requires_chartjs = true;
$requires_dataTables = true;
require_once __DIR__ . '/views/header.php';
require_once __DIR__ . '/views/navigation.php';

/**
 * Neues Depot anlegen (Offcanvas-Submit)
 */
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && ($_POST['action'] ?? '') === 'create_portfolio') {
	$name = trim($_POST['portfolio_name'] ?? '');
	$currency = trim($_POST['currency'] ?? '');
	if ($name !== '') {
		$stmtIns = $pdo->prepare("INSERT INTO depot_portfolios (name, currency) VALUES (:name, :currency)");
		$stmtIns->execute([
			':name'     => $name,
			':currency' => ($currency !== '' ? $currency : null)
		]);
		$newPid = (int)$pdo->lastInsertId();
		// Direkt auf das neue Depot wechseln
		header("Location: ?pid=" . $newPid);
		exit;
	}
}

$pid = isset($_GET['pid']) ? (int)$_GET['pid'] : null;

$stmtPort = $pdo->query("SELECT id, name FROM depot_portfolios ORDER BY name");
$portfolios = $stmtPort->fetchAll(PDO::FETCH_ASSOC);

if ($pid === null && !empty($portfolios)) {
	$pid = (int)$portfolios[0]['id'];
}

$activePortfolio = null;
if (!empty($pid) && !empty($portfolios)) {
	foreach ($portfolios as $pf) {
		if ((int)$pf['id'] === (int)$pid) {
			$activePortfolio = $pf;
			break;
		}
	}
}

if ($pid === null && !empty($portfolios)) {
	$pid = (int)$portfolios[0]['id'];
}

if ($pid === null) {
	$pid = 1;
}

// Depot-Einträge (gefiltert nach Portfolio)
$stmt = $pdo->prepare("
	SELECT *
	FROM depot_entries
	WHERE status = 'active' AND portfolio_id = :pid
	ORDER BY buy_date DESC
");
$stmt->execute([':pid' => $pid]);
$activeEntries = $stmt->fetchAll();

$stmtSold = $pdo->prepare("
	SELECT *
	FROM depot_entries
	WHERE status = 'sold' AND portfolio_id = :pid
	ORDER BY sell_date DESC
");
$stmtSold->execute([':pid' => $pid]);
$soldEntries = $stmtSold->fetchAll();

/**
 * Performance-Basiswerte (portfolio-spezifisch)
 * Annahme: depot_meta und depot_cash besitzen portfolio_id
 */
$stmtMeta = $pdo->prepare("SELECT meta_value FROM depot_meta WHERE meta_key='start_capital' AND portfolio_id = :pid");
$stmtMeta->execute([':pid' => $pid]);
$startCapital = (float)($stmtMeta->fetchColumn() ?: 0);

$stmtFlows = $pdo->prepare("
  SELECT COALESCE(SUM(
	CASE
	  WHEN type='deposit' THEN amount
	  WHEN type='withdraw' THEN -amount
	  ELSE 0
	END
  ),0)
  FROM depot_cash
  WHERE type IN ('deposit','withdraw') AND is_snapshot = 0 AND portfolio_id = :pid
");
$stmtFlows->execute([':pid' => $pid]);
$flowsSum = (float)$stmtFlows->fetchColumn();

$barCash = $startCapital + $flowsSum;

// Barbestand anhand Entries (gekauft/verkauft) justieren
foreach ($activeEntries as $e) {
	$barCash -= ((float)$e['buy_price'] * (float)$e['shares']) + (float)($e['fees'] ?? 0);
}
foreach ($soldEntries as $e) {
	$barCash -= ((float)$e['buy_price'] * (float)$e['shares']) + (float)($e['fees'] ?? 0);
	$barCash += ((float)($e['sell_price'] ?? 0) * (float)$e['shares']) - (float)($e['sell_fees'] ?? 0);
}

$realizedPnL = 0.0;
$totalBuyValueSold = 0.0;
foreach ($soldEntries as $se) {
	$pnl = ((float)$se['sell_price'] - (float)$se['buy_price']) * (float)$se['shares'];
	$realizedPnL += $pnl;
	$totalBuyValueSold += ((float)$se['buy_price'] * (float)$se['shares']);
}
$realizedPct = $totalBuyValueSold > 0 ? ($realizedPnL / $totalBuyValueSold) * 100 : 0;

// last_portfolio_value (portfolio-spezifisch)
$stmtTotal = $pdo->prepare("SELECT meta_value FROM depot_meta WHERE meta_key='last_portfolio_value' AND portfolio_id = :pid");
$stmtTotal->execute([':pid' => $pid]);
$totalValue = (float)$stmtTotal->fetchColumn();
if (!$totalValue) {
	$totalValue = $barCash;
}
$totalPerfAbs = $totalValue - $startCapital;
$totalPerfPct = $startCapital > 0 ? ($totalPerfAbs / $startCapital) * 100 : 0;

// Transaktions-Historie: Cashflows + Käufe + Verkäufe (portfolio-spezifisch)
$sql = "
SELECT 
  c.id,
  c.flow_date AS `date`,
  CASE 
	WHEN c.`type`='deposit'  THEN 'Einzahlung'
	WHEN c.`type`='withdraw' THEN 'Auszahlung'
	ELSE c.`type`
  END AS `type`,
  NULL AS symbol,
  CAST(0.00 AS DECIMAL(10,2)) AS shares,
  CASE 
	WHEN c.`type`='deposit'  THEN c.amount
	WHEN c.`type`='withdraw' THEN -c.amount
	ELSE c.amount
  END AS amount,
  c.note,
  c.`type` AS type_raw,
  'cash'  AS source
FROM depot_cash c
WHERE c.portfolio_id = :pid

UNION ALL

SELECT
  e.id,
  e.buy_date AS `date`,
  'Kauf'     AS `type`,
  e.symbol,
  e.shares   AS shares,
  -(e.shares*e.buy_price + COALESCE(e.fees,0)) AS amount,
  e.notes    AS note,
  NULL       AS type_raw,
  'buy'      AS source
FROM depot_entries e
WHERE e.status='active' AND e.portfolio_id = :pid

UNION ALL

SELECT
  e.id,
  e.sell_date AS `date`,
  'Verkauf'   AS `type`,
  e.symbol,
  e.shares    AS shares,
  (e.shares*e.sell_price - COALESCE(e.sell_fees,0)) AS amount,
  e.notes     AS note,
  NULL        AS type_raw,
  'sell'      AS source
FROM depot_entries e
WHERE e.status='sold' AND e.sell_date IS NOT NULL AND e.portfolio_id = :pid

ORDER BY `date` DESC
";
$stmtTx = $pdo->prepare($sql);
$stmtTx->execute([':pid' => (int)$pid]);
$allTransactions = $stmtTx->fetchAll(PDO::FETCH_ASSOC);
?>

<main class="flex-grow-1 container my-5">
	<div class="row">
		<div class="col-12">
			<div class="d-flex justify-content-between align-items-center mb-4">
				<h1 class="mb-0"><?= htmlspecialchars($activePortfolio['name'] ?? '') ?></h1>
				<div>
					<form method="get" class="d-inline-block me-2">
						<select name="pid" class="form-select form-select-sm" onchange="this.form.submit()">
						  <?php foreach ($portfolios as $pf): ?>
							<option value="<?= (int)$pf['id'] ?>" <?= ((int)$pf['id'] === (int)$pid) ? 'selected' : '' ?>>
							  <?= htmlspecialchars($pf['name'] ?? ('Depot #' . (int)$pf['id'])) ?>
							</option>
						  <?php endforeach; ?>
						</select>
					</form>
					<button class="btn btn-outline-success btn-sm me-2" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNewPortfolio">
					  Depot hinzufügen
					</button>
					<button class="btn btn-outline-success btn-sm me-2" data-bs-toggle="offcanvas" data-bs-target="#offcanvasAddEntry">
						Wert hinzufügen
					</button>
					<button class="btn btn-outline-secondary btn-sm" data-bs-toggle="offcanvas" data-bs-target="#offcanvasDepotSettings">
						<i class="fas fa-cog"></i>
					</button>
				</div>
			</div>
			<div class="row g-3 mb-4">
				<div class="col-12 col-sm-6 col-lg-3">
					<div class="card">
					<div class="card-body">
						<div class="text-muted small">Barbestand</div>
						<div class="h5 mb-0"><span id="kpiCash"><?= number_format($barCash, 2, ',', '.') ?></span></div>
					</div>
					</div>
				</div>
				<div class="col-12 col-sm-6 col-lg-3">
					<div class="card">
					<div class="card-body">
						<div class="text-muted small">Gesamt (Aktien + Cash + Assets)</div>
						<div class="h5 mb-0"><span id="kpiPortfolioValue">—</span></div>
					</div>
					</div>
				</div>
				<div class="col-12 col-sm-6 col-lg-3">
				  <div class="card">
					<div class="card-body">
					  <div class="text-muted small">Gesamtrendite</div>
					  <div class="h5 mb-0">
						<span id="kpiTotalReturnAbs">—</span>
						(<span id="kpiTotalReturnPct">—</span>)
					  </div>
					</div>
				  </div>
				</div>
				<div class="col-12 col-sm-6 col-lg-3">
					<div class="card">
					<div class="card-body">
						<div class="text-muted small">Realisierte Rendite</div>
						<div class="h5 mb-0">
						<span id="kpiRealized" class="<?= $realizedPnL >= 0 ? 'text-success' : 'text-danger' ?>">
							<?= number_format($realizedPnL, 2, ',', '.') ?> (<?= number_format($realizedPct, 2, ',', '.') ?> %)
						</span>
						</div>
					</div>
					</div>
				</div>
			</div>
		</div>
		<div class="col-12">
			<div class="h-200">
				<canvas id="depotPerformanceChart"></canvas>
			</div>
		</div>
		
		<div class="col-12 mt-4">
			<ul class="nav nav-tabs" id="depotTabs" role="tablist">
				<li class="nav-item" role="presentation">
					<button class="nav-link text-dark active" id="active-tab" data-bs-toggle="tab" data-bs-target="#active" type="button">Aktive Positionen</button>
				</li>
				<li class="nav-item" role="presentation">
					<button class="nav-link text-dark" id="sold-tab" data-bs-toggle="tab" data-bs-target="#sold" type="button">Verkaufte Positionen</button>
				</li>
				<li class="nav-item" role="presentation">
					<button class="nav-link text-dark" id="transcations-tab" data-bs-toggle="tab" data-bs-target="#transactions" type="button">Transaktionen</button>
				</li>
				<li class="nav-item" role="presentation">
					<button class="nav-link text-dark" id="manual-tab" data-bs-toggle="tab" data-bs-target="#manual" type="button" role="tab" aria-controls="manual">Manuelle Assets</button>
				</li>
				<li class="nav-item" role="presentation">
					<button class="nav-link text-dark" id="allocation-tab" data-bs-toggle="tab" data-bs-target="#allocation" type="button">Allokationen</button>
				</li>
			</ul>
		</div>

		<div class="tab-content mt-3">
			<div class="tab-pane fade show active" id="active" role="tabpanel">
				<div class="table-responsive">
					<table class="table" id="depotTableActive">
						<thead class="table-dark">
							<tr>
								<th>
									Symbol<br>
									<small class="fw-normal">ISIN</small>
								</th>
								<th>
									Kurs<br>
									<small class="fw-normal">Datum</small>
								</th>
								<th>
									Performance<br>
									<small class="fw-normal">seit Kauf</small>
								</th>
								<th>
									Stück<br>
									<small class="fw-normal">Kaufwert</small>
								</th>
								<th>
									Kaufkurs<br>
									<small class="fw-normal">Datum</small>
								</th>
								<th>
									Perf. %<br>
									<small class="fw-normal">Perf. $</small>
								</th>
								<th>
									Wert<br>
									<small class="fw-normal">Gewichtung</small>
								</th>
								<th>
									Stop Loss<br>
									<small class="fw-normal">Take Profit</small>
								</th>
								<th>
									Strategie<br>
									<small class="fw-normal">Notizen</small>
								</th>
								<th class="text-end">
									Aktion<br>
									<small class="fw-normal">Details</small>
								</th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ($activeEntries as $entry): ?>
								<tr data-id="<?= $entry['id'] ?>"
								data-shares="<?= htmlspecialchars($entry['shares']) ?>"
								data-buy_price="<?= htmlspecialchars($entry['buy_price']) ?>"
								class="align-middle">
									<td>
										<div class="d-flex align-items-center">
											<?php
											$imgFallback = '/assets/img/company-placeholder.webp';
											$imgSrc = (!empty($entry['image']) && filter_var($entry['image'], FILTER_VALIDATE_URL))
												? $entry['image']
												: $imgFallback;
											?>
											<a href="/aktienbewertung.php?symbol=<?= htmlspecialchars($entry['symbol']) ?>&target_pe=&asof=" 
											   target="_blank" 
											   rel="noopener" 
											   class="text-dark text-decoration-none">
												<img 
												  src="<?= htmlspecialchars($imgSrc) ?>" 
												  alt="Logo" 
												  width="32" 
												  height="32" 
												  class="me-2 rounded-circle border"
												  onerror="this.onerror=null;this.src='<?= htmlspecialchars($imgFallback) ?>';"
												>
											</a>
											<div>
												<a href="/aktienbewertung.php?symbol=<?= htmlspecialchars($entry['symbol']) ?>&target_pe=&asof=" target="_blank" rel="noopener" class="text-dark text-decoration-none">
													<strong><?= htmlspecialchars($entry['symbol']) ?></strong>
												</a>
												<small class="text-muted ms-1"><?= $entry['exchange'] !== null ? htmlspecialchars($entry['exchange']) : '' ?></small><br>
												<small class="text-muted"><?= $entry['asset_kind'] !== null ? htmlspecialchars($entry['asset_kind']) : '' ?><?= $entry['asset_kind'] != '' ? ' &middot; ' : '' ?><?= $entry['isin'] !== null ? htmlspecialchars($entry['isin']) : '' ?></small>
											</div>
										</div>
									</td>
									<td class="current-price" data-id="<?= $entry['id'] ?>">
										<span class="price">–</span><br>
										<small class="text-muted price-date">–</small>
									</td>
									<td>
										<canvas class="sparkline" data-symbol="<?= $entry['symbol'] ?>" width="100" height="30"></canvas>
									</td>
									<td>
										<?= number_format($entry['shares'], 2) ?><br>
										<small class="text-muted"><?= number_format($entry['shares'] * $entry['buy_price'], 2) ?></small>
									</td>
									<?php
										$buyDate = DateTime::createFromFormat('Y-m-d', $entry['buy_date']);
										$buyDateFormatted = $buyDate ? $buyDate->format('d.m.Y') : $entry['buy_date'];
									?>
									<td>
										<?= number_format($entry['buy_price'], 2) ?><br>
										<small class="text-muted"><?= htmlspecialchars($buyDateFormatted) ?></small>
									</td>
									<td class="performance-cell" data-id="<?= $entry['id'] ?>">
										<span class="performance-percent">–</span><br>
										<small class="text-muted performance-dollar">–</small>
									</td>
									<td class="current-value" data-id="<?= $entry['id'] ?>">
										<span>–</span><br>
										<small class="gewichtung text-muted">–</small>
									</td>
									<td class="sl-tp-cell" data-id="<?= $entry['id'] ?>">
									  <?php 
										$slRaw = ($entry['stop_price'] !== null && $entry['stop_price'] !== '') ? (float)$entry['stop_price'] : null;
										$tpRaw = ($entry['take_profit_price'] !== null && $entry['take_profit_price'] !== '') ? (float)$entry['take_profit_price'] : null;
										$slFmt = $slRaw !== null ? number_format($slRaw, 2, ',', '.') : '';
										$tpFmt = $tpRaw !== null ? number_format($tpRaw, 2, ',', '.') : '';
									  ?>
									  <span class="sl" <?= $slRaw !== null ? 'data-sl="'.$slRaw.'"' : '' ?>><?= $slFmt ?></span><br>
									  <span class="tp" <?= $tpRaw !== null ? 'data-tp="'.$tpRaw.'"' : '' ?>><?= $tpFmt ?></span>
									</td>
									<td>
										<small><?= htmlspecialchars($entry['strategy']) ?></small><br/>
										<?php if (!empty(trim($entry['notes']))): ?>
											<i class="fas fa-sticky-note text-secondary" data-bs-toggle="tooltip" title="<?= htmlspecialchars($entry['notes']) ?>"></i>
										<?php endif; ?>
									</td>
									<td class="text-end">
										<div class="dropdown">
											<button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
												Aktion
											</button>
											<ul class="dropdown-menu dropdown-menu-end">
												<li>
													<a href="#" class="dropdown-item editEntryBtn" data-entry='<?= htmlspecialchars(json_encode($entry, JSON_UNESCAPED_UNICODE), ENT_QUOTES) ?>'>
														Bearbeiten
													</a>
												</li>
												<li>
													<a href="#" class="dropdown-item sellEntryBtn" data-entry='<?= htmlspecialchars(json_encode($entry, JSON_UNESCAPED_UNICODE), ENT_QUOTES) ?>'>
														Verkaufen
													</a>
												</li>
												<li>
													<a href="#" class="dropdown-item deleteEntryBtn text-danger">
														Löschen
													</a>
												</li>
												<li><hr class="dropdown-divider"></li>
												<li>
													<a href="/aktienbewertung.php?symbol=<?= htmlspecialchars($entry['symbol']) ?>" class="dropdown-item">
														Analysieren
													</a>
												</li>
											</ul>
										</div>
									</td>
								</tr>
							<?php endforeach; ?>
						</tbody>
						<tfoot>
						<tr class="fw-semibold">
							<td colspan="3">Summe</td>
							<td>
								<span id="sumShares">—</span><br>
								<small class="text-muted"><span id="sumBuyValue">—</span></small>
							</td>
							<td></td>
							<td>
								<span id="sumUnrealizedPct">—</span><br>
								<small class="text-muted"><span id="sumUnrealizedUsd">—</span></small>
							</td>
							<td>
								<span id="sumCurrentValue">—</span><br>
								<small class="text-muted"><span id="sumWeight">100.00 %</span></small>
							</td>
							<td colspan="2"></td>
						</tr>
						</tfoot>
					</table>
				</div>
			</div>

			<div class="tab-pane fade" id="sold" role="tabpanel">
				<div class="table-responsive">
					<table class="table" id="depotTableSold">
						<thead class="table-dark">
							<tr>
							<th>
								Symbol<br>
								<small class="fw-normal">ISIN</small>
							</th>
							<th>
								Stück<br>
								<small class="fw-normal">Kaufwert</small>
							</th>
							<th>
								Kaufkurs<br>
								<small class="fw-normal">Datum</small>
							</th>
							<th>
								Verkaufskurs<br>
								<small class="fw-normal">Datum</small>
							</th>
							<th>
								Realisiert<br>
								<small class="fw-normal">G/V $</small>
							</th>
							<th>
								Strategie<br>
								<small class="fw-normal">Notizen</small>
							</th>
							<th class="text-end">
								Aktion<br>
								<small class="fw-normal">Details</small>
							</th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ($soldEntries as $entry): ?>
							<?php
								$buyDateObj  = DateTime::createFromFormat('Y-m-d', $entry['buy_date']);
								$sellDateObj = DateTime::createFromFormat('Y-m-d', $entry['sell_date']);
								$buyDateDE   = $buyDateObj  ? $buyDateObj->format('d.m.Y')  : $entry['buy_date'];
								$sellDateDE  = $sellDateObj ? $sellDateObj->format('d.m.Y') : $entry['sell_date'];
					
								$shares      = (float)$entry['shares'];
								$buyPrice    = (float)$entry['buy_price'];
								$sellPrice   = (float)$entry['sell_price'];
								$buyValue    = $shares * $buyPrice;
								$realizedUSD = ($sellPrice - $buyPrice) * $shares;
								$realizedPct = $buyValue > 0 ? ($realizedUSD / $buyValue * 100) : 0;
								$gvClassUSD  = $realizedUSD >= 0 ? 'text-success' : 'text-danger';
								$gvClassPct  = $realizedPct >= 0 ? 'text-success' : 'text-danger';
							?>
							<tr class="align-middle"
								data-shares="<?= htmlspecialchars($shares) ?>"
								data-buy_value="<?= htmlspecialchars($buyValue) ?>"
								data-realized_usd="<?= htmlspecialchars($realizedUSD) ?>">
								<td>
								<div class="d-flex align-items-center">
									<?php if (!empty($entry['image'])): ?>
									<a href="/aktienbewertung.php?symbol=<?= htmlspecialchars($entry['symbol']) ?>" target="_blank" rel="noopener" class="text-dark text-decoration-none">
										<img src="<?= htmlspecialchars($entry['image']) ?>" alt="Logo" width="32" height="32" class="me-2 rounded-circle border">
									</a>
									<?php endif; ?>
									<div>
									<a href="/aktienbewertung.php?symbol=<?= htmlspecialchars($entry['symbol']) ?>" target="_blank" rel="noopener" class="text-dark text-decoration-none">
										<strong><?= htmlspecialchars($entry['symbol']) ?></strong>
									</a>
									<small class="text-muted ms-1"><?= htmlspecialchars($entry['exchange']) ?></small><br>
									<small class="text-muted"><?= htmlspecialchars($entry['isin']) ?></small>
									</div>
								</div>
								</td>
								<td>
									<?= number_format($shares, 2, ',', '.') ?><br>
									<small class="text-muted"><?= number_format($buyValue, 2, ',', '.') ?></small>
								</td>
								<td>
									<?= number_format($buyPrice, 2, ',', '.') ?><br>
									<small class="text-muted"><?= htmlspecialchars($buyDateDE) ?></small>
								</td>
								<td>
									<?= number_format($sellPrice, 2, ',', '.') ?><br>
									<small class="text-muted"><?= htmlspecialchars($sellDateDE) ?></small>
								</td>
								<td>
									<span class="<?= $gvClassPct ?>"><?= number_format($realizedPct, 2, ',', '.') ?> %</span><br>
									<small class="<?= $gvClassUSD ?>"><?= ($realizedUSD >= 0 ? '+' : '–') . number_format(abs($realizedUSD), 2, ',', '.') ?></small>
								</td>
								<td>
									<small><?= htmlspecialchars($entry['strategy']) ?></small><br/>
									<?php if (!empty(trim($entry['notes']))): ?>
										<i class="fas fa-sticky-note text-secondary" data-bs-toggle="tooltip" title="<?= htmlspecialchars($entry['notes']) ?>"></i>
									<?php endif; ?>
								</td>
								<td class="text-end">
								<div class="dropdown">
									<button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
										Aktion
									</button>
									<ul class="dropdown-menu dropdown-menu-end">
										<li>
											<a class="dropdown-item soldEditBtn"
											href="#"
											data-entry='<?= htmlspecialchars(json_encode($entry, JSON_UNESCAPED_UNICODE), ENT_QUOTES) ?>'>
												Bearbeiten
											</a>
										</li>
										<li>
											<a class="dropdown-item text-danger soldDeleteBtn"
											href="#"
											data-id="<?= (int)$entry['id'] ?>">
												Löschen
											</a>
										</li>
										<li><hr class="dropdown-divider"></li>
										<li>
											<a class="dropdown-item" href="/aktienbewertung.php?symbol=<?= htmlspecialchars($entry['symbol']) ?>" target="_blank">
											Analysieren
											</a>
										</li>
									</ul>
								</div>
								</td>
							</tr>
							<?php endforeach; ?>
						</tbody>
						<tfoot>
							<tr class="fw-semibold">
							<td>Summe</td>
							<td>
								<span id="soldSumShares">—</span><br>
								<small class="text-muted"><span id="soldSumBuyValue">—</span></small>
							</td>
							<td></td>
							<td></td>
							<td>
								<span id="soldSumPct">—</span><br>
								<small class="text-muted"><span id="soldSumUsd">—</span></small>
							</td>
							<td colspan="2"></td>
							</tr>
						</tfoot>
					</table>
				</div>
			</div>
			
			<div class="tab-pane fade" id="transactions" role="tabpanel" aria-labelledby="transactions-tab">
			  <div class="table-responsive">
				<table class="table align-middle" id="transactionsTable">
				  <thead class="table-dark">
					<tr>
					  <th>Datum</th>
					  <th>Typ</th>
					  <th>Symbol</th>
					  <th>Stück</th>
					  <th>Betrag (USD)</th>
					  <th>Notiz</th>
					  <th>Aktion</th>
					</tr>
				  </thead>
				  <tbody>
					<?php if (!empty($allTransactions)): ?>
					  <?php foreach ($allTransactions as $t): ?>
						<tr>
						  <td><?= htmlspecialchars($t['date']) ?></td>
						  <td><?= htmlspecialchars($t['type']) ?></td>
						  <td><?= htmlspecialchars($t['symbol'] ?? '') ?></td>
						  <td><?= (($t['source'] ?? '') === 'cash' || !isset($t['shares'])) ? '' : number_format((float)$t['shares'], 2, ',', '.') ?></td>
						  <td><?= number_format((float)$t['amount'], 2, ',', '.') ?></td>
						  <td><?= htmlspecialchars($t['note'] ?? '') ?></td>
						  <td>
							  <?php if (($t['source'] ?? '') === 'cash' && !empty($t['type_raw'])): ?>
								<button
								  class="btn btn-sm btn-outline-secondary editCashflowBtn"
								  data-bs-toggle="offcanvas"
								  data-bs-target="#offcanvasEditCashflow"
								  data-cash='<?= json_encode([
									"id"           => (int)$t["id"],
									"type"         => $t["type_raw"] ?? ($t["type"] ?? ''),
									"amount"       => (float)$t["amount"],
									"date"         => $t["date"],
									"note"         => $t["note"] ?? '',
									"portfolio_id" => (int)$pid
								  ], JSON_UNESCAPED_UNICODE) ?>'>
								  Bearbeiten
								</button>
							  <?php endif; ?>
						  </td>
						</tr>
					  <?php endforeach; ?>
					<?php endif; ?>
				  </tbody>
				</table>
			  </div>
			</div>
			
			<div class="tab-pane fade" id="manual" role="tabpanel" aria-labelledby="manual-tab">
				<div class="d-flex justify-content-between align-items-center mb-2">
					<h5 class="mb-0">Manuelle Assets</h5>
					<button class="btn btn-outline-success btn-sm" id="btnManualAssetNew">
						Asset hinzufügen
					</button>
				</div>
				<div class="table-responsive">
					<table class="table" id="depotTableManual">
						<thead class="table-dark">
							<tr>
								<th>Typ<br><small class="fw-normal">Kategorie</small></th>
								<th>Name<br><small class="fw-normal">Notiz</small></th>
								<th class="text-end">Aktueller Wert<br><small class="fw-normal">Portfolio‑Währung</small></th>
								<th class="text-end">Gewichtung<br><small class="fw-normal">% vom Gesamt</small></th>
								<th class="text-end">Aktion</th>
							</tr>
						</thead>
						<tbody></tbody>
						<tfoot>
						  <tr class="fw-semibold">
							<td colspan="2">Summe</td>
							<td class="text-end"><span id="manualSumValue">—</span></td>
							<td class="text-end"><span id="manualSumWeight">—</span></td>
							<td></td>
						  </tr>
						</tfoot>
					</table>
				</div>
			</div>
			
			<div class="tab-pane fade" id="allocation" role="tabpanel">
				<div class="row g-4">
					<div class="col-md-6">
					  <div class="card">
						<div class="card-body text-center">
							<h6 class="mb-0">Gewichtung nach Wert</h6>
							<div id="wrapAllocValue" class="w-100 position-relative h-300">
								<canvas id="chartAllocValue" class="d-block w-100"></canvas>
							</div>
						</div>
					  </div>
					</div>
					<div class="col-md-6">
					  <div class="card">
						<div class="card-body text-center">
							<h6 class="mb-0">Gewichtung nach Assetklasse</h6>
							<div id="wrapAllocValue" class="w-100 position-relative h-300">
								<canvas id="chartAllocKind" class="d-block w-100"></canvas>
							</div>
						</div>
					  </div>
					</div>
				  </div>
				  <div id="allocMeta" data-cash="<?= number_format($flowsSum, 2, '.', '') ?>"></div>
			</div>
		</div>
	</div>
</main>
<?php require_once __DIR__ . '/views/footer.php'; ?>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasNewPortfolio">
	<div class="offcanvas-header">
		<h5 class="offcanvas-title">Neues Depot hinzufügen</h5>
		<button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
	</div>
	<div class="offcanvas-body">
		<form id="newPortfolioForm">
		<div class="mb-3">
			<label class="form-label">Depotname</label>
			<input type="text" name="name" class="form-control" placeholder="Mein neues Depot" required>
		</div>
		<button type="submit" class="btn btn-dark w-100">
		Depot anlegen
		</button>
		</form>
	</div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasEditCashflow">
  <div class="offcanvas-header">
	<h5 class="offcanvas-title">Transaktion bearbeiten</h5>
	<button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
  </div>
  <div class="offcanvas-body">
	<form id="cashflowEditForm">
	  <input type="hidden" name="id" id="cfEditId">
	  <input type="hidden" name="portfolio_id" value="<?= (int)$pid ?>">
	  <div class="mb-3">
		<label class="form-label">Typ</label>
		<select name="type" id="cfEditType" class="form-select" required>
		  <option value="deposit">Einzahlung</option>
		  <option value="withdraw">Auszahlung</option>
		</select>
	  </div>
	  <div class="mb-3">
		<label class="form-label">Betrag</label>
		<input type="number" step="0.01" name="amount" id="cfEditAmount" class="form-control" required>
	  </div>
	  <div class="mb-3">
		<label class="form-label">Datum</label>
		<input type="date" name="date" id="cfEditDate" class="form-control" required>
	  </div>
	  <div class="mb-3">
		<label class="form-label">Notiz</label>
		<input type="text" name="note" id="cfEditNote" class="form-control">
	  </div>
	  <div class="d-grid gap-2">
		<button type="submit" class="btn btn-dark">Speichern</button>
		<!-- Optionaler Löschbutton -->
		<button type="button" class="btn btn-outline-danger" id="cashflowDeleteBtn">Löschen</button>
	  </div>
	</form>
  </div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasAddEntry">
	<div class="offcanvas-header">
		<h5 class="offcanvas-title">Wert hinzufügen</h5>
		<button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
	</div>
	<div class="offcanvas-body">
		<ul class="nav nav-tabs" id="offcanvasTabs" role="tablist">
			<li class="nav-item" role="presentation">
				<button class="nav-link active text-dark" data-bs-toggle="tab" data-bs-target="#tabAdd" type="button" role="tab">Wert hinzufügen</button>
			</li>
			<li class="nav-item" role="presentation">
				<button class="nav-link text-dark" data-bs-toggle="tab" data-bs-target="#tabMM" type="button" role="tab">Positionsgröße</button>
			</li>
		</ul>
		<div class="tab-content mt-3">
			<div class="tab-pane fade show active" id="tabAdd" role="tabpanel">
				<form id="addEntryForm">
					<input type="hidden" name="portfolio_id" value="<?= (int)$pid ?>">
					<div class="mb-3">
						<label class="form-label">Symbol *</label>
						<input name="symbol" class="form-control symbol-autocomplete" placeholder="AAPL" required id="addSymbol">
					</div>
					<div class="mb-3">
						<label class="form-label">Art</label>
						<input type="text" name="asset_kind" class="form-control" placeholder="Art">
					</div>
					<div class="mb-3">
						<label class="form-label">Strategie</label>
						<input name="strategy" class="form-control" placeholder="Strategie">
					</div>
					<div class="row">
						<div class="col-md-6 mb-3">
							<label class="form-label">Stück *</label>
							<input type="number" step="1" name="shares" class="form-control" placeholder="Stück" required>
						</div>
						<div class="col-md-6 mb-3">
							<label class="form-label">Kaufkurs *</label>
							<input type="number" step="0.01" name="buy_price" class="form-control" placeholder="Kaufkurs" required>
						</div>
					</div>
					<div class="row">
						<div class="col-md-6 mb-3">
						<label for="buyStopPrice" class="form-label">Stop-Loss Kurs</label>
						<input type="number" step="0.01" class="form-control" id="buyStopPrice" name="stop_price" placeholder="Stop-Loss Kurs">
						</div>
						<div class="col-md-6 mb-3">
						<label for="buyTakeProfitPrice" class="form-label">Take-Profit Kurs</label>
						<input type="number" step="0.01" class="form-control" id="buyTakeProfitPrice" name="take_profit_price" placeholder="Take-Profit Kurs">
						</div>
					</div>
					<div class="mb-3">
						<label class="form-label">Kaufdatum *</label>
						<input type="date" name="buy_date" class="form-control" placeholder="Kaufdatum" required>
					</div>
					<div class="mb-3">
						<label class="form-label">Spesen</label>
						<input type="number" step="0.01" name="fees" class="form-control" placeholder="Spesen">
					</div>
					<div class="mb-3">
						<label class="form-label">Notiz</label>
						<textarea name="notes" rows="3" class="form-control"></textarea>
					</div>
					<button type="submit" class="btn btn-dark w-100">
						Speichern
					</button>
				</form>
			</div>
			<div class="tab-pane fade" id="tabMM" role="tabpanel">
				<div class="row">
					<div class="col-md-6 mb-3">
						<label class="form-label">Kapital</label>
						<input type="number" class="form-control" id="mmCapital" placeholder="100000">
					</div>
					<div class="col-md-6 mb-3">
						<label class="form-label">Risiko %</label>
						<input type="number" class="form-control" id="mmRisk" placeholder="0.5">
					</div>
				</div>
				<div class="row">
					<div class="col-md-6 mb-3">
						<label class="form-label">Einstiegskurs</label>
						<input type="number" class="form-control" id="mmEntry" placeholder="Einstiegskurs">
					</div>
					<div class="col-md-6 mb-3">
						<label class="form-label">Volatilität (%)</label>
						<input type="number" class="form-control" id="mmVolatility" placeholder="10">
					</div>
				</div>
				<div class="col-12 mb-3">
					<label class="form-label">Richtung</label>
					<select id="mmDirection" class="form-select">
						<option value="long">Long</option>
						<option value="short">Short</option>
					</select>
				</div>
				<button class="btn btn-dark w-100" id="mmCalcBtn">Berechnen</button>
				
				<div id="mmResult" class="small mt-3"></div>
			</div>
		</div>
	</div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasEditEntry">
	<div class="offcanvas-header">
		<h5 class="offcanvas-title">
			Eintrag bearbeiten: <span id="editSymbolTitle" class="text-uppercase text-muted"></span>
			<small id="editExchangeInfo" class="d-block text-secondary"></small>
		</h5>
		<button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
	</div>
	<div class="offcanvas-body">
		<form id="editEntryForm">
			<input type="hidden" name="id">
			<input type="hidden" name="portfolio_id" value="<?= (int)$pid ?>">
			
			<div class="mb-3">
			  <label class="form-label">Symbol *</label>
			  <input name="symbol" class="form-control symbol-autocomplete" id="editSymbol">
			</div>
			<div class="mb-3">
				<label class="form-label">Art</label>
				<input type="text" name="asset_kind" id="editAssetKind" class="form-control" placeholder="Art">
			</div>
			<div class="mb-3">
				<label class="form-label">Strategie</label>
				<input name="strategy" class="form-control">
			</div>
			<div class="row">
				<div class="col-md-6 mb-3">
					<label class="form-label">Stück</label>
					<input type="number" step="1" name="shares" class="form-control">
				</div>
				<div class="col-md-6 mb-3">
					<label class="form-label">Kaufkurs</label>
					<input type="number" step="0.01" name="buy_price" class="form-control">
				</div>
			</div>
			<div class="row">
				<div class="col-md-6 mb-3">
					<label class="form-label">Stop-Loss Kurs</label>
					<input type="number" step="0.01" name="stop_price" class="form-control">
				</div>
				<div class="col-md-6 mb-3">
					<label class="form-label">Take-Profit Kurs</label>
					<input type="number" step="0.01" name="take_profit_price" class="form-control">
				</div>
			</div>
			<div class="row">
				<div class="col-md-6 mb-3">
					<label class="form-label">Kaufdatum</label>
					<input type="date" name="buy_date" class="form-control">
				</div>
				<div class="col-md-6 mb-3">
					<label class="form-label">Spesen</label>
					<input type="number" step="0.01" name="fees" class="form-control">
				</div>
			</div>
			<div class="mb-3">
				<label class="form-label">Notiz</label>
				<textarea name="notes" class="form-control" rows="3"></textarea>
			</div>
			<button type="submit" class="btn btn-dark w-100">Speichern</button>
		</form>
	</div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasSell" aria-labelledby="offcanvasSellLabel">
  <div class="offcanvas-header">
	<h5 class="offcanvas-title" id="offcanvasSellLabel">
		Position verkaufen: <span id="sellSymbolTitle" class="text-uppercase text-muted"></span>
	</h5>
	<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
	<form id="sellForm">
	  <input type="hidden" name="id" id="sellId">
	  <input type="hidden" name="portfolio_id" value="<?= (int)$pid ?>">

	  <div class="mb-3">
		<label for="sellSymbol" class="form-label">Symbol</label>
		<input type="text" class="form-control" id="sellSymbol" name="symbol" readonly>
	  </div>

	  <div class="mb-3">
		<label for="sellAvailableShares" class="form-label">Verfügbare Stücke</label>
		<input type="number" class="form-control" id="sellAvailableShares" readonly>
	  </div>

	  <div class="mb-3">
		<label for="sellShares" class="form-label">Verkaufte Stücke</label>
		<input type="number" class="form-control" id="sellShares" name="shares" required min="0.01" step="0.01">
	  </div>

	  <div class="mb-3">
		<label for="sellPrice" class="form-label">Verkaufskurs ($)</label>
		<input type="number" class="form-control" id="sellPrice" name="price" required step="0.01">
	  </div>

	  <div class="mb-3">
		<label for="sellDate" class="form-label">Verkaufsdatum</label>
		<input type="date" class="form-control" id="sellDate" name="date" required>
	  </div>
	  
	  <div class="mb-3">
		<label for="sellFees" class="form-label">Spesen (optional)</label>
		<input type="number" class="form-control" id="sellFees" name="fees" step="0.01" placeholder="0.00">
	  </div>

	  <div class="mb-3">
		<label for="sellNotes" class="form-label">Notiz (optional)</label>
		<textarea class="form-control" id="sellNotes" name="notes" rows="2"></textarea>
	  </div>

	  <div class="d-grid">
		<button type="submit" class="btn btn-dark">Verkaufen</button>
	  </div>
	</form>
  </div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasEditSold" aria-labelledby="offcanvasEditSoldLabel">
  <div class="offcanvas-header">
	<h5 class="offcanvas-title" id="offcanvasEditSoldLabel">
	  Verkauf bearbeiten: <span id="soldEditSymbol" class="text-uppercase text-muted"></span>
	</h5>
	<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
	<form id="editSoldForm">
	  <input type="hidden" name="id" id="soldEditId">
	  <input type="hidden" name="portfolio_id" value="<?= (int)$pid ?>">

	  <div class="mb-3">
		<label class="form-label">Symbol</label>
		<input type="text" class="form-control" id="soldEditSymbolInput" readonly>
	  </div>

	 <div class="row">
	   <div class="col-md-6 mb-3">
		 <label class="form-label">Stückzahl (max.)</label>
		 <input type="number" class="form-control" step="0.01" min="0" name="sell_shares" id="soldEditSellShares" required>
	   </div>
	   <div class="col-md-6 mb-3">
		 <label class="form-label">Verkaufskurs ($)</label>
		 <input type="number" step="0.01" class="form-control" name="sell_price" id="soldEditPrice" required>
	   </div>
	 </div>
	 
	 <div class="row">
	   <div class="col-md-6 mb-3">
		 <label class="form-label">Spesen ($)</label>
		 <input type="number" step="0.01" class="form-control" name="sell_fees" id="soldEditFees" placeholder="0.00">
	   </div>
	   <div class="col-md-6 mb-3">
		 <label class="form-label">Verkaufsdatum</label>
		 <input type="date" class="form-control" name="sell_date" id="soldEditDate" required>
	   </div>
	 </div>
	 
	 <div class="mb-3 p-2 border rounded bg-light">
	   <small class="text-muted">Rechenhilfe:</small><br>
	   <div>Bruttoerlös: <strong id="calcGross">–</strong></div>
	   <div>Spesen: <strong id="calcFees">–</strong></div>
	   <div>Nettoerlös: <strong id="calcNet">–</strong></div>
	   <div>Performance: <strong id="calcPerf">–</strong> %</div>
	 </div>
	 
	  <div class="mb-3">
		<label class="form-label">Notiz</label>
		<textarea class="form-control" name="notes" id="soldEditNotes" rows="2"></textarea>
	  </div>

	  <div class="d-grid">
		<button type="submit" class="btn btn-dark">Speichern</button>
	  </div>
	</form>
  </div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasManualAsset">
	<div class="offcanvas-header">
		<h5 class="offcanvas-title" id="manualAssetTitle">Manuelles Asset</h5>
		<button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
	</div>
	<div class="offcanvas-body">
		<form id="manualAssetForm">
			<input type="hidden" name="id" value="">
			<input type="hidden" name="portfolio_id" value="<?= (int)$pid ?>">
			<div class="mb-3">
				<label class="form-label">Name *</label>
				<input type="text" name="label" class="form-control" placeholder="Manuelles Asset" required>
			</div>
			<div class="row">
				<div class="col-md-6 mb-3">
					<label class="form-label">Kategorie</label>
					<select name="category" class="form-select">
						<option>Aktien</option>
						<option>Anleihen</option>
						<option>Bargeld</option>
						<option>Crypto-Währungen</option>
						<option>Edelmetalle</option>
						<option>ETF</option>
						<option>ETC</option>
						<option>Fonds</option>
						<option>Immobilien</option>
						<option>Rohstoffe</option>
						<option selected>Sonstige</option>
					</select>
				</div>
				<div class="col-md-6 mb-3">
					<label class="form-label">Wert *</label>
					<input type="number" step="0.01" name="value" class="form-control" placeholder="0,00" required>
				</div>
			</div>
			<div class="row">
				<div class="col-md-6 mb-3">
					<label class="form-label">Währung</label>
					<input type="text" name="currency" class="form-control" placeholder="EUR" value="EUR">
				</div>
				<div class="col-md-6 mb-3">
					<label class="form-label">Notiz</label>
					<input type="text" name="notes" class="form-control" placeholder="optional">
				</div>
			</div>
			<div class="d-grid gap-2">
				<button class="btn btn-dark" type="submit">Speichern</button>
				<button class="btn btn-outline-danger d-none" id="btnManualAssetDelete" type="button">Löschen</button>
			</div>
		</form>
	</div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasDepotSettings">
	<div class="offcanvas-header">
		<h5 class="offcanvas-title">Depot-Einstellungen</h5>
		<button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
	</div>
	<div class="offcanvas-body">
		<form id="renamePortfolioForm" class="mb-3">
			<input type="hidden" name="portfolio_id" value="<?= (int)$pid ?>">
			<div class="mb-3">
				<label class="form-label">Depot umbenennen</label>
				<input type="text" name="name" class="form-control"
						placeholder="Neuer Name"
						value="<?= htmlspecialchars($activePortfolio['name'] ?? '') ?>" required>
			</div>
			<button type="submit" class="btn btn-dark w-100">Namen speichern</button>
		</form>
		<hr class="my-4">
		
		<form id="startCapitalForm" class="mb-4">
			<div class="mb-3">
				<label class="form-label">Startkapital</label>
				<input type="number" step="0.01" name="capital" class="form-control" value="<?= number_format($startCapital, 2, '.', '') ?>">
				<input type="hidden" name="portfolio_id" value="<?= (int)$pid ?>">
			</div>
			<button type="submit" class="btn btn-dark w-100">Startkapital speichern</button>
		</form>
		<hr class="my-4">
		
		<form id="cashflowForm">
			<input type="hidden" name="portfolio_id" value="<?= (int)$pid ?>">
			<div class="row g-2">
			<div class="col-12">
				<label class="form-label">Typ</label>
				<select name="type" class="form-select">
				<option value="deposit">Einzahlung</option>
				<option value="withdraw">Auszahlung</option>
				</select>
			</div>
			<div class="col-6">
				<label class="form-label">Betrag</label>
				<input type="number" step="0.01" name="amount" class="form-control" required>
			</div>
			<div class="col-6">
				<label class="form-label">Datum</label>
				<input type="date" name="date" class="form-control" value="<?= date('Y-m-d') ?>">
			</div>
			<div class="col-12">
				<label class="form-label">Notiz (optional)</label>
				<input type="text" name="note" class="form-control">
			</div>
			</div>
			<button type="submit" class="btn btn-dark w-100 mt-3">Transaktion buchen</button>
		</form>
		<hr class="my-4">
		
	    <div class="border rounded p-3">
			<h6 class="text-danger mb-2"><i class="fas fa-triangle-exclamation me-1"></i>Depot löschen</h6>
			<p class="small text-muted mb-2">
			  Dadurch werden <strong>alle Einträge, Verkäufe, Transaktionen und Einstellungen</strong> dieses Depots endgültig gelöscht. Dieser Vorgang kann nicht rückgängig gemacht werden.
			</p>
			<form id="deletePortfolioForm" class="d-grid gap-2">
			  <input type="hidden" name="portfolio_id" value="<?= (int)$pid ?>">
			  <input type="text" class="form-control" id="deleteConfirmText"
					 placeholder="Zum Bestätigen: DEPOT LÖSCHEN" aria-label="Bestätigung">
			  <button type="submit" class="btn btn-outline-danger" disabled id="deletePortfolioBtn">
				Depot unwiderruflich löschen
			  </button>
			</form>
		</div>
	</div>
</div>

<script>
	function todayISO() {
	return new Date().toISOString().split('T')[0];
	}
</script>

<script>
document.addEventListener("DOMContentLoaded", function () {
	const btnCalc = document.getElementById("mmCalcBtn");
	const resultDiv = document.getElementById("mmResult");

	btnCalc.addEventListener("click", function (e) {
		e.preventDefault();

		const capital     = parseFloat(document.getElementById("mmCapital").value) || 0;
		const riskPercent = parseFloat(document.getElementById("mmRisk").value) || 0;
		const direction   = document.getElementById("mmDirection")?.value || "long";
		const entryPrice  = parseFloat(document.getElementById("mmEntry").value) || 0;
		const volatility  = parseFloat(document.getElementById("mmVolatility").value) || 0;

		if (capital <= 0 || riskPercent <= 0 || entryPrice <= 0 || volatility <= 0) {
			alert("Bitte alle Felder ausfüllen.");
			return;
		}

		fetch("/execute/money-management/money-management_calculate.php", {
			method: "POST",
			headers: { "Content-Type": "application/x-www-form-urlencoded" },
			body: new URLSearchParams({
				capital,
				risk_percent: riskPercent,
				direction,
				entry_price: entryPrice,
				volatility
			})
		})
		.then(res => res.json())
		.then(data => {
			if (data.error) {
				resultDiv.innerHTML = `<span class="text-danger">${data.error}</span>`;
				return;
			}

			// Formatter für deutsche Zahlen
			const nf0 = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 0 });
			const nf2 = new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

			resultDiv.innerHTML = `
				<ul class="list-group list-group-flush text-start">
					<li class="list-group-item px-0 bg-transparent"><strong>Anzahl Aktien:</strong> ${nf0.format(data.anzahl_aktien)}</li>
					<li class="list-group-item px-0 bg-transparent"><strong>Maximales Risiko:</strong> ${nf2.format(data.max_risiko)} €</li>
					<li class="list-group-item px-0 bg-transparent"><strong>Verlust pro Aktie:</strong> ${nf2.format(data.verlust_pro_aktie)} €</li>
					<li class="list-group-item px-0 bg-transparent"><strong>Investiertes Kapital:</strong> ${nf2.format(data.investiertes_kapital)} €</li>
					<li class="list-group-item px-0 bg-transparent"><strong>Tatsächliches Risiko:</strong> ${nf2.format(data.tatsaechliches_risiko)} €</li>
					<li class="list-group-item px-0 bg-transparent"><strong>Stop-Loss-Kurs:</strong> ${nf2.format(data.stop_loss_kurs)} €</li>
					<li class="list-group-item px-0 bg-transparent"><strong>Möglicher Gewinn (€) bei Zielkurs:</strong> ${nf2.format(data.potenzieller_gewinn)} €</li>
					<li class="list-group-item px-0 bg-transparent"><strong>Möglicher Gewinn (%) bei Zielkurs:</strong> ${nf2.format(data.prozentualer_gewinn)} %</li>
					<li class="list-group-item px-0 bg-transparent"><strong>Volatilität:</strong> ${nf2.format(data.volatilitaet)} %</li>
					<li class="list-group-item px-0 pb-0 bg-transparent"><strong>CRV:</strong> ${nf2.format(data.crv)}</li>
				</ul>
			`;
		})
		.catch(err => {
			console.error("Fehler bei der Berechnung:", err);
			resultDiv.innerHTML = `<span class="text-danger">Berechnungsfehler</span>`;
		});
	});
});
</script>

<script>
document.addEventListener('DOMContentLoaded', () => {
	
	// Neues Depot hinzufügen
	document.getElementById('newPortfolioForm')?.addEventListener('submit', (e) => {
		e.preventDefault();
		const fd = new FormData(e.target);
		fetch('/execute/depot/depot_add_portfolio.php', { method: 'POST', body: fd })
		.then(async (r) => {
			const text = await r.text();
			// Versuche JSON zu parsen …
			try {
			const j = JSON.parse(text);
			if (j.success) { location.reload(); }
			else { alert(j.error || 'Konnte Depot nicht hinzufügen.'); }
			} catch {
			// … oder erwarte "success" als Plain-Text
			if (text.trim().toLowerCase() === 'success') {
				location.reload();
			} else {
				alert(text || 'Konnte Depot nicht hinzufügen.');
			}
			}
		})
		.catch(() => alert('Netzwerkfehler beim Anlegen des Depots.'));
	});
	
	// Depot umbenennen
	document.getElementById('renamePortfolioForm')?.addEventListener('submit', (e) => {
	  e.preventDefault();
	  const fd = new FormData(e.target);
	  fetch('/execute/depot/depot_rename_portfolio.php', { method: 'POST', body: fd })
		.then(r => r.json())
		.then(j => { if (j.success) location.reload(); else alert(j.error || 'Konnte Depot nicht umbenennen.'); })
		.catch(() => alert('Netzwerkfehler beim Umbenennen.'));
	});
	
	// Delete confirm: Button nur bei „DEPOT LÖSCHEN“ aktiv
	const delInput = document.getElementById('deleteConfirmText');
	const delBtn   = document.getElementById('deletePortfolioBtn');
	if (delInput && delBtn) {
		delInput.addEventListener('input', () => {
		delBtn.disabled = (delInput.value.trim().toUpperCase() !== 'DEPOT LÖSCHEN');
		});
	}
	
	// Depot löschen
	document.getElementById('deletePortfolioForm')?.addEventListener('submit', (e) => {
		e.preventDefault();
		if (!confirm('Wirklich dieses Depot mit allen Daten löschen? Das kann NICHT rückgängig gemacht werden.')) return;
		const fd = new FormData(e.target);
		fetch('/execute/depot/depot_delete_portfolio.php', { method: 'POST', body: fd })
		.then(r => r.json())
		.then(j => { if (j.success) window.location.href = '/depot.php'; else alert(j.error || 'Konnte Depot nicht löschen.'); })
		.catch(() => alert('Netzwerkfehler beim Löschen.'));
	});
	
	// Startkapital speichern
	document.getElementById('startCapitalForm')?.addEventListener('submit', (e) => {
		e.preventDefault();
		const fd = new FormData(e.target);
		fd.append('portfolio_id', '<?= (int)$pid ?>');
		fetch('/execute/depot/depot_start_capital_update.php', { method: 'POST', body: fd })
		.then(r => r.json())
		.then(j => { if (j.ok || j.success) location.reload(); });
	});

	// Einzahlung/Auszahlung buchen
	document.getElementById('cashflowForm')?.addEventListener('submit', (e) => {
		e.preventDefault();
		const fd = new FormData(e.target);
		fd.append('portfolio_id', '<?= (int)$pid ?>'); // <= HINZU
		fetch('/execute/depot/depot_cashflow_create.php', { method: 'POST', body: fd })
		.then(r => r.json())
		.then(j => { if (j.ok || j.success) location.reload(); });
	});
  
	// Transaktion bearbeiten
	const cfEditOffcanvas = new bootstrap.Offcanvas('#offcanvasEditCashflow');
	const cfEditForm = document.getElementById('cashflowEditForm');
  
	document.querySelectorAll('.editCashflowBtn').forEach(btn => {
		btn.addEventListener('click', () => {
		const cf = JSON.parse(btn.dataset.cash);
		cfEditForm.id.value = cf.id;
		cfEditForm.type.value = cf.type || 'deposit';
		cfEditForm.amount.value = cf.amount ?? '';
		cfEditForm.date.value = cf.date || '';
		cfEditForm.note.value = cf.note || '';
		if (cf.portfolio_id && cfEditForm.portfolio_id) cfEditForm.portfolio_id.value = cf.portfolio_id;
		cfEditOffcanvas.show();
		});
	});
  
	// Transaktion speichern
	cfEditForm?.addEventListener('submit', (e) => {
		e.preventDefault();
		const fd = new FormData(cfEditForm);
		fetch('/execute/depot/depot_cashflow_update.php', { method: 'POST', body: fd })
		.then(r => r.json())
		.then(j => { if (j.success) location.reload(); else alert(j.error || 'Fehler beim Aktualisieren.'); })
		.catch(() => alert('Netzwerkfehler beim Aktualisieren.'));
	});
  
	// Transaktion löschen
	document.getElementById('cashflowDeleteBtn')?.addEventListener('click', () => {
		if (!confirm('Diese Transaktion wirklich löschen?')) return;
		const fd = new FormData();
		fd.append('id', cfEditForm.id.value);
		if (cfEditForm.portfolio_id) fd.append('portfolio_id', cfEditForm.portfolio_id.value);
		fetch('/execute/depot/depot_cashflow_delete.php', { method: 'POST', body: fd })
		.then(r => r.json())
		.then(j => { if (j.success) location.reload(); else alert(j.error || 'Fehler beim Löschen.'); })
		.catch(() => alert('Netzwerkfehler beim Löschen.'));
	});
});
</script>

<script>
function debounce(fn, ms=300){ let t; return (...a)=>{ clearTimeout(t); t=setTimeout(()=>fn(...a), ms); }; }

document.addEventListener('DOMContentLoaded', () => {
  const symbolInput   = document.getElementById('addSymbol');
  const buyPriceInput = document.querySelector('#addEntryForm input[name="buy_price"]');
  const buyDateInput  = document.querySelector('#addEntryForm input[name="buy_date"]');

  if (!symbolInput || !buyPriceInput) return;

  const fetchAndFill = debounce(() => {
	const sym = (symbolInput.value || '').trim().toUpperCase();
	if (!sym) return;

	fetch(`/execute/depot/depot_quote.php?symbol=${encodeURIComponent(sym)}&pid=<?= (int)$pid ?>&enforce=0`)
	  .then(r => r.ok ? r.json() : null)
	  .then(q => {
		if (q && typeof q.price === 'number') {
		  buyPriceInput.value = q.price.toFixed(2);
		  if (buyDateInput && !buyDateInput.value) {
			buyDateInput.value = new Date().toISOString().split('T')[0];
		  }
		}
	  })
	  .catch(() => { /* still ok */ });
  }, 350);

  symbolInput.addEventListener('blur', fetchAndFill);
  symbolInput.addEventListener('input', fetchAndFill);
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
	const tableActive = new DataTable('#depotTableActive', {
		order: [[1, 'asc']],
		pageLength: 50,
		lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "Alle"]],
		language: {
			url: "assets/js/data-tables_de-DE.json"
		},
		columnDefs: [
			{ orderable: false, targets: [2, 7, -1] }
		]
	});

	const tableSold = new DataTable('#depotTableSold', {
	  order: [[3, 'desc']],
	  pageLength: 50,
	  lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "Alle"]],
	  language: { url: "assets/js/data-tables_de-DE.json" },
	  columnDefs: [
		{ orderable: false, targets: [5, 6] }
	  ]
	});
	
	if (window.jQuery && $('#transactionsTable').length) {
		$('#transactionsTable').DataTable({
		  order: [[0, 'desc']],
		  pageLength: 50,
		  lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "Alle"]],
		  language: {
			url: 'assets/js/data-tables_de-DE.json',
			emptyTable: 'Keine Transaktionen vorhanden.'
		  }
		});
	}
});
</script>

<script>
	document.addEventListener('DOMContentLoaded', function () {
		const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
		tooltipTriggerList.forEach(function (tooltipTriggerEl) {
			new bootstrap.Tooltip(tooltipTriggerEl);
		});
	});
</script>

<script>
	document.addEventListener('DOMContentLoaded', function () {
		const addForm = document.getElementById('addEntryForm');
		const cashForm = document.getElementById('updateCashForm');
	
		if (addForm) {
			addForm.addEventListener('submit', function (e) {
				e.preventDefault();
				const formData = new FormData(addForm);
	
				fetch('/execute/depot/depot_add_entry.php', {
					method: 'POST',
					body: formData
				})
				.then(res => res.text())
				.then(response => {
				  if (response === 'success') {
					fetch('/execute/depot/depot_update_performance.php')
					  .finally(() => location.reload());
				  } else {
					alert('Fehler: ' + response);
				  }
				});
			});
		}
	
		if (cashForm) {
			cashForm.addEventListener('submit', function (e) {
				e.preventDefault();
				const formData = new FormData(cashForm);
	
				fetch('/execute/depot/depot_update_cash.php', {
					method: 'POST',
					body: formData
				})
				.then(res => res.text())
				.then(response => {
					if (response === 'success') {
						location.reload();
					} else {
						alert('Fehler: ' + response);
					}
				});
			});
		}
	});
</script>

<script>
	document.addEventListener('DOMContentLoaded', function () {
		const editForm = document.getElementById('editEntryForm');
		const editOffcanvas = new bootstrap.Offcanvas('#offcanvasEditEntry');
	
		document.querySelectorAll('.editEntryBtn').forEach(btn => {
			btn.addEventListener('click', () => {
				const entry = JSON.parse(btn.dataset.entry);
				document.getElementById('editSymbolTitle').textContent = entry.symbol ?? '';
				document.getElementById('editExchangeInfo').textContent = `${entry.isin ?? ''} · ${entry.exchange ?? ''}`;
				editForm.id.value = entry.id;
				editForm.symbol.value = entry.symbol || '';
				editForm.strategy.value = entry.strategy ?? '';
				editForm.asset_kind.value = entry.asset_kind ?? '';
				editForm.shares.value = entry.shares;
				editForm.buy_price.value = entry.buy_price;
				editForm.stop_price.value = entry.stop_price ?? '';
				editForm.take_profit_price.value = entry.take_profit_price ?? '';
				editForm.buy_date.value = entry.buy_date;
				editForm.fees.value = entry.fees ?? 0.00;
				editForm.notes.value = entry.notes ?? '';
				editOffcanvas.show();
			});
		});
	
		editForm.addEventListener('submit', function (e) {
		  e.preventDefault();
		  const formData = new FormData(editForm);
		  formData.append('portfolio_id', '<?= (int)$pid ?>');
		  fetch('/execute/depot/depot_update_entry.php', { method: 'POST', body: formData })
			.then(r => r.text())
			.then(t => {
			  if (t === 'success') {
				fetch('/execute/depot/depot_update_performance.php').finally(() => location.reload());
			  } else {
				alert('Fehler: ' + t);
			  }
			});
		});
	
		document.querySelectorAll('.deleteEntryBtn').forEach(btn => {
			btn.addEventListener('click', () => {
				const row = btn.closest('tr');
				const entryId = row.dataset.id;
				if (confirm('Eintrag wirklich löschen?')) {
					fetch('/execute/depot/depot_delete_entry.php', {
						method: 'POST',
						headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
						body: `id=${entryId}&pid=<?= (int)$pid ?>`
					})
					.then(res => res.text())
					.then(response => {
						if (response === 'success') {
							location.reload();
						} else {
							alert('Fehler: ' + response);
						}
					});
				}
			});
		});
		
		document.querySelectorAll('.sellEntryBtn').forEach(button => {
		  button.addEventListener('click', () => {
			const entry = JSON.parse(button.dataset.entry);
		
			document.getElementById('sellSymbolTitle').textContent = entry.symbol || '';
			document.getElementById('offcanvasSellLabel').textContent = `Position verkaufen: ${entry.symbol || ''}`;
			document.getElementById('sellId').value = entry.id;
			document.getElementById('sellSymbol').value = entry.symbol;
			document.getElementById('sellAvailableShares').value = parseFloat(entry.shares).toFixed(2);
			document.getElementById('sellShares').value = '';
			document.getElementById('sellPrice').value = '';
			document.getElementById('sellNotes').value = '';
		
			const sellDateField = document.getElementById('sellDate');
			if (!sellDateField.value) sellDateField.value = todayISO();
		
			fetch(`/execute/depot/depot_quote.php?symbol=${encodeURIComponent(entry.symbol)}&pid=<?= (int)$pid ?>&enforce=1`)
			  .then(r => r.ok ? r.json() : null)
			  .then(q => { if (q && typeof q.price === 'number') { document.getElementById('sellPrice').value = q.price.toFixed(2); }});
		
			new bootstrap.Offcanvas('#offcanvasSell').show();
		  });
		});
		
		document.getElementById('openAddEntryBtn')?.addEventListener('click', () => {
		  const buyDateField = document.querySelector('#addEntryForm input[name="buy_date"]');
		  if (buyDateField && !buyDateField.value) buyDateField.value = todayISO();
		});
		
		document.getElementById('sellForm')?.addEventListener('submit', async function (e) {
		  e.preventDefault();
		  const formData = new FormData(this);
		  formData.append('portfolio_id', '<?= (int)$pid ?>');
		  try {
			const res = await fetch('/execute/depot/depot_sell_entry.php', { method: 'POST', body: formData });
			const text = await res.text();
			let data;
			try { data = JSON.parse(text); } catch { alert('Ungültige Serverantwort:\n' + text); return; }
			if (!res.ok || !data.success) { alert('Fehler: ' + (data.error || 'Unbekannter Fehler')); return; }
			fetch('/execute/depot/depot_update_performance.php').finally(() => location.reload());
		  } catch {
			alert('Fehler beim Verkauf (Netzwerk).');
		  }
		});

		document.querySelectorAll('.editEntryBtn').forEach(btn => {
		  btn.addEventListener('click', () => {
			const entry = JSON.parse(btn.dataset.entry);
			editForm.id.value = entry.id;
			editForm.strategy.value = entry.strategy ?? '';
			editForm.shares.value = entry.shares ?? '';
			editForm.buy_price.value = entry.buy_price ?? '';
			editForm.buy_date.value = entry.buy_date ?? '';
			editForm.fees.value = (entry.fees ?? '') === '' ? '' : entry.fees;
			editForm.notes.value = entry.notes ?? '';
			editForm.stop_price.value = entry.stop_price ?? '';
			editForm.take_profit_price.value = entry.take_profit_price ?? '';
			
			editOffcanvas.show();
		  });
		});
		
	});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
  document.querySelectorAll('.soldEditBtn').forEach(btn => {
	btn.addEventListener('click', (e) => {
	  e.preventDefault();
	  let entry;
	  try { entry = JSON.parse(btn.dataset.entry || '{}'); }
	  catch { alert('Ungültige Daten im Eintrag.'); return; }

	  const nf2 = new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
	  const toDE = (iso) => {
		if (!iso) return '';
		if (iso.includes('.')) return iso; // schon dd.mm.yyyy
		const p = iso.split('-'); // yyyy-mm-dd[..]
		return p.length >= 3 ? `${p[2].slice(0,2)}.${p[1]}.${p[0]}` : iso;
	  };
	  const toISO = (d) => {
		if (!d) return '';
		if (d.includes('-')) return d.slice(0,10); // schon ISO, ggfs. Zeit abschneiden
		const p = d.split('.');
		return p.length === 3 ? `${p[2]}-${p[1]}-${p[0]}` : d;
	  };

	  // ---- DOM-Refs (prüfen!) ----
	  const ocEl   = document.getElementById('offcanvasEditSold');
	  const idEl   = document.getElementById('soldEditId');
	  const symHdr = document.getElementById('soldEditSymbol');
	  const symInp = document.getElementById('soldEditSymbolInput');

	  const sharesRO    = document.getElementById('soldEditShares');
	  const buyPriceRO  = document.getElementById('soldEditBuyPrice');
	  const buyValueRO  = document.getElementById('soldEditBuyValue');
	  const buyDateRO   = document.getElementById('soldEditBuyDate');

	  const sellShares  = document.getElementById('soldEditSellShares');
	  const sellPrice   = document.getElementById('soldEditPrice');
	  const sellFees    = document.getElementById('soldEditFees');
	  const sellDate    = document.getElementById('soldEditDate');
	  const notesEl     = document.getElementById('soldEditNotes');

	  const calcGrossEl = document.getElementById('calcGross');
	  const calcFeesEl  = document.getElementById('calcFees');
	  const calcNetEl   = document.getElementById('calcNet');
	  const calcPerfEl  = document.getElementById('calcPerf');

	  if (!ocEl || !idEl || !symHdr || !symInp) {
		console.error('Offcanvas-Elemente fehlen.');
		return;
	  }

	  const shares   = Number(entry.shares || 0);
	  const buyPrice = Number(entry.buy_price || 0);
	  const buyValue = shares * buyPrice;
	  const _sellFees = (entry.sell_fees !== null && entry.sell_fees !== undefined) ? Number(entry.sell_fees) : 0.00;

	  // ---- befüllen ----
	  idEl.value = entry.id ?? '';
	  symHdr.textContent = entry.symbol || '';
	  symInp.value = entry.symbol || '';

	  if (sharesRO)    sharesRO.value   = nf2.format(shares);
	  if (buyPriceRO)  buyPriceRO.value = nf2.format(buyPrice);
	  if (buyValueRO)  buyValueRO.value = nf2.format(buyValue) + ' USD';
	  if (buyDateRO)   buyDateRO.value  = toDE(entry.buy_date || '');

	  if (sellShares) {
		sellShares.value = shares;
		sellShares.setAttribute('max', String(shares));
	  }
	  if (sellPrice) sellPrice.value = (entry.sell_price ?? '').toString();
	  if (sellFees)  sellFees.value  = _sellFees.toString();
	  if (sellDate)  sellDate.value  = toISO(entry.sell_date || '');
	  if (notesEl)   notesEl.value   = entry.notes ?? '';

	  // ---- Rechenhilfe ----
	  const updateCalc = () => {
		if (!sellShares || !sellPrice || !sellFees) return;
		const qty   = parseFloat(sellShares.value) || 0;
		const price = parseFloat(sellPrice.value) || 0;
		const fees  = parseFloat(sellFees.value)  || 0;
		const gross = qty * price;
		const net   = gross - fees;
		const perfPct = buyPrice > 0 ? ((price - buyPrice) / buyPrice) * 100 : 0;

		if (calcGrossEl) calcGrossEl.textContent = nf2.format(gross);
		if (calcFeesEl)  calcFeesEl.textContent  = nf2.format(fees);
		if (calcNetEl)   calcNetEl.textContent   = nf2.format(net);
		if (calcPerfEl)  calcPerfEl.textContent  = nf2.format(perfPct);
	  };

	  // Events nur binden, wenn Felder existieren
	  if (sellShares) sellShares.addEventListener('input', updateCalc);
	  if (sellPrice)  sellPrice.addEventListener('input', updateCalc);
	  if (sellFees)   sellFees.addEventListener('input', updateCalc);

	  // Initial rechnen
	  updateCalc();

	  // ---- Offcanvas zeigen ----
	  const offcanvas = new bootstrap.Offcanvas(ocEl);
	  offcanvas.show();
	});
  });

  document.getElementById('editSoldForm')?.addEventListener('submit', async function (e) {
	e.preventDefault();
	const formData = new FormData(this);
	formData.append('portfolio_id', '<?= (int)$pid ?>');
	try {
	  const res = await fetch('/execute/depot/depot_sell_entry.php', { method: 'POST', body: formData });
	  const txt = await res.text();
	  let data;
	  try { data = JSON.parse(txt); } catch { alert('Ungültige Serverantwort:\n' + txt); return; }
	  if (!res.ok || !data.success) { alert('Fehler: ' + (data.error || 'Unbekannter Fehler')); return; }
	  fetch('/execute/depot/depot_update_performance.php').finally(() => location.reload());
	} catch {
	  alert('Fehler beim Speichern.');
	}
  });

  document.querySelectorAll('.soldDeleteBtn').forEach(btn => {
	btn.addEventListener('click', async (e) => {
	  e.preventDefault();
	  const id = btn.dataset.id;
	  if (!id) return;

	  if (!confirm('Diesen Verkauf wirklich löschen und rückgängig machen?')) return;

	  try {
		const res = await fetch('/execute/depot/depot_delete_sold_entry.php', {
		  method: 'POST',
		  headers: {'Content-Type':'application/x-www-form-urlencoded'},
		  body: `id=${encodeURIComponent(id)}&pid=<?= (int)$pid ?>`
		});
		const txt = await res.text();
		let data;
		try { data = JSON.parse(txt); } catch { alert('Ungültige Serverantwort:\n' + txt); return; }
		if (!res.ok || !data.success) { alert('Fehler: ' + (data.error || 'Unbekannter Fehler')); return; }

		fetch('/execute/depot/depot_update_performance.php').finally(() => location.reload());
	  } catch {
		alert('Fehler beim Löschen.');
	  }
	});
  });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
	fetch('/execute/depot/depot_entry_metrics.php?pid=<?= (int)$pid ?>')
		.then(response => response.json())
		.then(metrics => {
			for (const [id, data] of Object.entries(metrics)) {
				const priceCell = document.querySelector(`.current-price[data-id="${id}"]`);
				const perfCell = document.querySelector(`.performance-cell[data-id="${id}"]`);
				const valueCell = document.querySelector(`.current-value[data-id="${id}"]`);
				const sltpCell = document.querySelector(`.sl-tp-cell[data-id="${id}"]`);

				if (priceCell) {
					const priceSpan = priceCell.querySelector('.price');
					const priceDate = priceCell.querySelector('.price-date');

					if (priceSpan) priceSpan.textContent = data.current_price.toFixed(2);

					if (priceDate && data.price_date) {
						const parts = data.price_date.split('-'); // ["2025", "08", "08"]
						if (parts.length === 3) {
							priceDate.textContent = `${parts[2]}.${parts[1]}.${parts[0]}`; // "08.08.2025"
						} else {
							priceDate.textContent = data.price_date; // fallback
						}
					}
				}

				if (valueCell) {
					const span = valueCell.querySelector('span');
					const small = valueCell.querySelector('.gewichtung');
					if (span) span.textContent = data.current_value.toFixed(2);
					if (small) small.textContent = data.gewichtung.toFixed(2) + ' %';
				}

				if (perfCell) {
					const pctEl = perfCell.querySelector('.performance-percent');
					const usdEl = perfCell.querySelector('.performance-dollar');

					if (pctEl) {
						pctEl.textContent = data.performance_percent.toFixed(2) + ' %';
						pctEl.classList.add(data.performance_percent >= 0 ? 'text-success' : 'text-danger');
					}

					if (usdEl) {
						const val = data.performance_dollar.toFixed(2);
						usdEl.textContent = (data.performance_dollar >= 0 ? '+' : '–') + Math.abs(val);
						usdEl.classList.add(data.performance_dollar >= 0 ? 'text-success' : 'text-danger');
					}
				}
				
				if (sltpCell) {
				  const slEl = sltpCell.querySelector('.sl');
				  const tpEl = sltpCell.querySelector('.tp');
				  const cp   = Number(data.current_price);
				
				  sltpCell.classList.remove('sl-hit','tp-hit');
				
				  // --- STOP ---
				  if (slEl && slEl.dataset.sl !== undefined) {
					const sl = Number(slEl.dataset.sl);
					const slHit = !Number.isNaN(sl) && !Number.isNaN(cp) && cp <= sl;
				
					slEl.classList.toggle('text-danger', slHit);
					slEl.classList.toggle('fw-semibold', slHit);
				
				  }
				
				  // --- TAKE PROFIT ---
				  if (tpEl && tpEl.dataset.tp !== undefined) {
					const tp = Number(tpEl.dataset.tp);
					const tpHit = !Number.isNaN(tp) && !Number.isNaN(cp) && cp >= tp;
				
					tpEl.classList.toggle('text-success', tpHit);
					tpEl.classList.toggle('fw-semibold', tpHit);
				  }
				}
			}
		});
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const nf2 = new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const BAR_CASH = parseFloat('<?= number_format($barCash, 2, '.', '') ?>');

  fetch('/execute/depot/depot_entry_metrics.php?pid=<?= (int)$pid ?>')
	.then(response => response.json())
	.then(metrics => {
	  let sumCurrentValue = 0;
	  let sumBuyValue = 0;
	  let sumShares = 0;

	  for (const [id, data] of Object.entries(metrics)) {
		const row = document.querySelector(`tr[data-id="${id}"]`);
		const priceCell = document.querySelector(`.current-price[data-id="${id}"]`);
		const perfCell = document.querySelector(`.performance-cell[data-id="${id}"]`);
		const valueCell = document.querySelector(`.current-value[data-id="${id}"]`);

		if (priceCell) {
		  const priceSpan = priceCell.querySelector('.price');
		  const priceDate = priceCell.querySelector('.price-date');
		  if (priceSpan) priceSpan.textContent = data.current_price.toFixed(2);
		  if (priceDate && data.price_date) {
			const parts = data.price_date.split('-');
			priceDate.textContent = (parts.length === 3) ? `${parts[2]}.${parts[1]}.${parts[0]}` : data.price_date;
		  }
		}

		if (valueCell) {
		  const span = valueCell.querySelector('span');
		  const small = valueCell.querySelector('.gewichtung');
		  if (span) span.textContent = data.current_value.toFixed(2);
		  if (small) small.textContent = data.gewichtung.toFixed(2) + ' %';
		}

		if (perfCell) {
		  const pctEl = perfCell.querySelector('.performance-percent');
		  const usdEl = perfCell.querySelector('.performance-dollar');
		  if (pctEl) {
			pctEl.textContent = data.performance_percent.toFixed(2) + ' %';
			pctEl.classList.add(data.performance_percent >= 0 ? 'text-success' : 'text-danger');
		  }
		  if (usdEl) {
			const val = data.performance_dollar.toFixed(2);
			usdEl.textContent = (data.performance_dollar >= 0 ? '+' : '–') + Math.abs(val);
			usdEl.classList.add(data.performance_dollar >= 0 ? 'text-success' : 'text-danger');
		  }
		}

		if (row) {
		  const shares = parseFloat(row.dataset.shares || '0');
		  const buyPrice = parseFloat(row.dataset.buy_price || '0');
		  const buyValue = shares * buyPrice;

		  sumShares += shares;
		  sumBuyValue += buyValue;
		}
		sumCurrentValue += (data.current_value || 0);
	  }

	  const elSumShares = document.getElementById('sumShares');
	  const elSumBuyValue = document.getElementById('sumBuyValue');
	  const elSumUnrealizedUsd = document.getElementById('sumUnrealizedUsd');
	  const elSumUnrealizedPct = document.getElementById('sumUnrealizedPct');
	  const elSumCurrentValue = document.getElementById('sumCurrentValue');

	  const unrealized = sumCurrentValue - sumBuyValue;
	  const unrealizedPct = (sumBuyValue > 0) ? (unrealized / sumBuyValue * 100) : 0;

	  if (elSumShares) elSumShares.textContent = nf2.format(sumShares);
	  if (elSumBuyValue) elSumBuyValue.textContent = nf2.format(sumBuyValue);
	  if (elSumUnrealizedUsd) {
		elSumUnrealizedUsd.textContent = (unrealized >= 0 ? '+' : '–') + nf2.format(Math.abs(unrealized));
		elSumUnrealizedUsd.classList.add(unrealized >= 0 ? 'text-success' : 'text-danger');
	  }
	  if (elSumUnrealizedPct) {
		elSumUnrealizedPct.textContent = nf2.format(unrealizedPct) + ' %';
		elSumUnrealizedPct.classList.add(unrealizedPct >= 0 ? 'text-success' : 'text-danger');
	  }
	  if (elSumCurrentValue) elSumCurrentValue.textContent = nf2.format(sumCurrentValue);

	  const kpiStocksValue = document.getElementById('kpiStocksValue');
	  const kpiCash = document.getElementById('kpiCash');
	  const kpiPortfolioValue = document.getElementById('kpiPortfolioValue');

	  if (kpiStocksValue) kpiStocksValue.textContent = nf2.format(sumCurrentValue);
	  
	  // Baseline für spätere Recalc
	  window.__kpiStocksSum__ = sumCurrentValue;
	  window.__kpiCash__ = BAR_CASH;
	  
	  // falls manuelle Assets schon geladen sind, gleich mitrechnen
	  const manualFromRows = Array.isArray(window.__manual_alloc_rows__) ? window.__manual_alloc_rows__ : [];
	  const manualSum = manualFromRows.reduce((s,a)=> s + (Number(a.value)||0), 0);
	  
	  if (kpiPortfolioValue) kpiPortfolioValue.textContent = nf2.format(sumCurrentValue + BAR_CASH + manualSum);
	  
	  // signal für spätere Listener (optional)
	  document.dispatchEvent(new CustomEvent('kpiBaselineReady'));
	  
	  // ----- Allokationen als BAR-CHARTS (ohne TR-Daten zu ändern) -----
	  // ----- Allokationen als BAR-CHARTS (inkl. Aktien + Cash + Manuelle Assets) -----
	  (() => {
		let chartsBuilt = false;
		const fmt = new Intl.NumberFormat('de-DE',{minimumFractionDigits:2,maximumFractionDigits:2});
	  
		// buildAllocationCharts(metrics) ODER buildAllocationCharts({force:true})
		window.buildAllocationCharts = function(arg1,arg2){
		  const isOpts = arg1 && typeof arg1==='object' && !Array.isArray(arg1) && ('force' in arg1);
		  const opts = isOpts ? arg1 : (arg2||{});
		  const force = !!opts.force;
		  if (chartsBuilt && !force) return;
		  chartsBuilt = true;
	  
		  const metricsRef = isOpts ? (window.metrics||{}) : (arg1||window.metrics||{});
	  
		  // --- Aktien/aktive Positionen aus Tabelle aggregieren ---
		  const bySymbol = Object.create(null);
		  const symbolKind = Object.create(null);
		  const rows = document.querySelectorAll('#depotTableActive tbody tr');
	  
		  for (const tr of rows) {
			const btn = tr.querySelector('.editEntryBtn[data-entry]');
			if (!btn) continue;
			let entry; try { entry = JSON.parse(btn.dataset.entry); } catch { continue; }
			const id   = String(entry.id);
			const sym  = entry.symbol || id;
			const kind = entry.asset_kind || 'Equity';
			const m = metricsRef ? metricsRef[id] : null;
			if (!m) continue;
			const val = Number(m.current_value)||0;
			bySymbol[sym] = (bySymbol[sym]||0) + val;
			symbolKind[sym] = kind;
		  }
	  
		  // --- Manuelle Assets mergen (einmal pro Label) ---
		  const manual = Array.isArray(window.__manual_alloc_rows__)? window.__manual_alloc_rows__ : [];
		  for (const a of manual) {
			const label = a.label || 'Manuelles Asset';
			const val   = Number(a.value)||0;
			const kind  = a.kind || 'Other';
			bySymbol[label] = (bySymbol[label]||0) + val;
			symbolKind[label] = kind;
		  }
	  
		  // --- Cash hinzufügen (Position + Klasse) ---
		  const cash = Number(document.getElementById('allocMeta')?.dataset.cash || 0);
		  if (!Number.isNaN(cash) && cash !== 0) {
			bySymbol['Cash'] = (bySymbol['Cash']||0) + cash;
			symbolKind['Cash'] = 'Cash';
		  }
	  
		  // --- Chart 1: Gewichtung nach Wert (pro Position) ---
		  const labelsValue = Object.keys(bySymbol);
		  const dataValue   = labelsValue.map(s => bySymbol[s]);
	  
		  // --- Chart 2: Gewichtung nach Assetklasse ---
		  const byKind = Object.create(null);
		  for (const sym of labelsValue) {
			const k = symbolKind[sym] || 'Unkategorisiert';
			byKind[k] = (byKind[k]||0) + bySymbol[sym];
		  }
		  const labelsKind = Object.keys(byKind);
		  const dataKind   = labelsKind.map(k => byKind[k]);
		  
		  function setAutoHeightByCount(wrapperEl, count, per=28, base=140, max=900){
			if (!wrapperEl) return;
			wrapperEl.style.height = Math.min(max, base + count * per) + 'px';
		  }
	  
		  // --- Render ---
		  const wrapValue = document.getElementById('wrapAllocValue');
		  setAutoHeightByCount(wrapValue, labelsValue.length);
		  
		  const ctxValue = document.getElementById('chartAllocValue');
		  if (ctxValue) {
			if (window.__chartAllocValue) window.__chartAllocValue.destroy();
			window.__chartAllocValue = new Chart(ctxValue, {
			  type: 'bar',
			  data: { labels: labelsValue, datasets: [{ label: 'Wert', data: dataValue, backgroundColor: 'rgba(0,0,0,0.7)' }] },
			  options: {
				indexAxis: 'y',
				responsive: true,
				maintainAspectRatio: false,
				plugins: { legend: { display: false }, tooltip: { callbacks: { label: c => ` ${fmt.format(c.parsed.x)}` } } },
				scales: { x: { ticks: { callback: v => fmt.format(v) } } }
			  }
			});
		  }
		  
		  const wrapKind = document.getElementById('wrapAllocKind');
		  setAutoHeightByCount(wrapKind, labelsKind.length);
		  
		  const ctxKind = document.getElementById('chartAllocKind');
		  if (ctxKind) {
			if (window.__chartAllocKind) window.__chartAllocKind.destroy();
			window.__chartAllocKind = new Chart(ctxKind, {
			  type: 'bar',
			  data: { labels: labelsKind, datasets: [{ label: 'Wert', data: dataKind, backgroundColor: 'rgba(0,0,0,0.7)' }] },
			  options: {
				indexAxis: 'y',
				responsive: true,
				maintainAspectRatio: false,
				plugins: { legend: { display: false }, tooltip: { callbacks: { label: c => ` ${fmt.format(c.parsed.x)}` } } },
				scales: { x: { ticks: { callback: v => fmt.format(v) } } }
			  }
			});
		  }
		};
	  })();
	  
	  buildAllocationCharts(metrics);

	});
});
</script>

<script>
(function() {
	const pid = <?= (int)$pid ?>;
	const nf2 = new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
	
	let manualAssets = [];
	
	async function loadManualAssets() {
	const res = await fetch(`/execute/depot/depot_manual_asset_list.php?pid=${pid}`);
	const json = await res.json();
	if (!json.success) throw new Error(json.error || 'Fehler beim Laden manueller Assets');
	manualAssets = json.data || [];
	
	window.__manual_alloc_rows__ = (manualAssets || []).map(r => ({
	  label: r.label, value: Number(r.value)||0, kind: r.category||'Other'
	}));
	if (window.buildAllocationCharts) window.buildAllocationCharts({force:true});
	if (window.buildAllocationByKindChart) window.buildAllocationByKindChart({force:true});
	if (window.buildAllocationByPositionChart) window.buildAllocationByPositionChart({force:true});
	
	renderManualAssetsTable();
	updateKPIsWithManualAssets();
	injectManualIntoAllocation();
	
	function recalcPortfolioKpi() {
	  const nf2 = new Intl.NumberFormat('de-DE',{minimumFractionDigits:2,maximumFractionDigits:2});
	  const stocks = (typeof window.__kpiStocksSum__ === 'number') ? window.__kpiStocksSum__ : getCurrentStocksValue();
	  const cash   = (typeof window.__kpiCash__ === 'number') ? window.__kpiCash__ : getBarCash();
	  const total  = stocks + cash + getManualTotal();
	  const el = document.getElementById('kpiPortfolioValue');
	  if (el) el.textContent = nf2.format(total);
	}
	recalcPortfolioKpi();
	document.addEventListener('kpiBaselineReady', recalcPortfolioKpi);
	
}function renderManualAssetsTable() {
	const tbody = document.querySelector('#depotTableManual tbody');
	if (!tbody) return;
	tbody.innerHTML = '';
	
	const totalPortfolio = getCurrentStocksValue() + getBarCash() + getManualTotal();
	
	manualAssets.forEach(row => {
		const tr = document.createElement('tr');
		tr.className = 'align-middle';
		tr.dataset.id = row.id;
		tr.dataset.value = (row.value || 0);
		tr.dataset.category = row.category || '';
		
		const gewichtung = totalPortfolio > 0 ? (row.value / totalPortfolio) * 100 : 0;
		
		tr.innerHTML = `
		<td>
		<div><strong>${row.category || 'Other'}</strong></div>
		<small class="text-muted">Manuell</small>
		</td>
		<td>
		<div>${escapeHtml(row.label || '')}</div>
		<small class="text-muted">${escapeHtml(row.notes || '')}</small>
		</td>
		<td class="text-end">${nf2.format(row.value || 0)}</td>
		<td class="text-end">${nf2.format(gewichtung)} %</td>
		<td class="text-end">
		<button class="btn btn-sm btn-outline-dark" data-action="edit">Bearbeiten</button>
		</td>`;
		tbody.appendChild(tr);
	});
	
	const manualTotal   = getManualTotal();
	const portfolioTotal = getCurrentStocksValue() + getBarCash() + manualTotal;
	
	const sumValEl = document.getElementById('manualSumValue');
	const sumWgtEl = document.getElementById('manualSumWeight');
	
	if (sumValEl) sumValEl.textContent = nf2.format(manualTotal);
	if (sumWgtEl) sumWgtEl.textContent = nf2.format(portfolioTotal > 0 ? (manualTotal/portfolioTotal*100) : 0) + ' %';
}

function getCurrentStocksValue() {
	const el = document.getElementById('kpiStocksValue');
	const raw = (el?.textContent || '').replace(/\./g, '').replace(',', '.');
	const val = parseFloat(raw);
	return Number.isFinite(val) ? val : 0;
}

function getBarCash() {
	const el = document.getElementById('kpiCash');
	const raw = (el?.textContent || '').replace(/\./g, '').replace(',', '.');
	const val = parseFloat(raw);
	return Number.isFinite(val) ? val : 0;
}

function getManualTotal() {
	return manualAssets.reduce((sum, r) => sum + (Number(r.value) || 0), 0);
}

function updateKPIsWithManualAssets() {
  const elPortfolio = document.getElementById('kpiPortfolioValue');
  if (!elPortfolio) return;

  const total = getCurrentStocksValue() + getBarCash() + getManualTotal();
  const fmt = new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  elPortfolio.textContent = fmt.format(total);

  // Optional: Untertitel „Gesamt (Aktien + Cash)“ -> „… + Manuell“
  const sub = document.querySelector('#cardPortfolio .card-subtitle, #kpiPortfolioSubtitle, #cardPortfolio small');
  if (sub && /Gesamt\s*\(Aktien\s*\+\s*Cash\)/i.test(sub.textContent)) {
	sub.textContent = 'Gesamt (Aktien + Cash + Manuell)';
  }
}

function injectManualIntoAllocation() {
	if (typeof window.buildAllocationCharts !== 'function') return;
	
	const rowsManual = manualAssets.map(r => ({
		label: r.label || 'Manuelles Asset',
		value: Number(r.value) || 0,
		kind: r.category || 'Other'
	}));
	
	window.__manual_alloc_rows__ = rowsManual;

	window.buildAllocationCharts({});
}

// Offcanvas-Handling
const offcanvasEl = document.getElementById('offcanvasManualAsset');
const bsCanvas = offcanvasEl ? new bootstrap.Offcanvas(offcanvasEl) : null;

document.getElementById('btnManualAssetNew')?.addEventListener('click', () => {
	resetManualForm();
	document.getElementById('manualAssetTitle').textContent = 'Manuelles Asset anlegen';
	document.getElementById('btnManualAssetDelete').classList.add('d-none');
	bsCanvas?.show();
});

document.getElementById('depotTableManual')?.addEventListener('click', (ev) => {
	const btn = ev.target.closest('[data-action="edit"]');
	if (!btn) return;
	const tr = btn.closest('tr');
	const id = tr?.dataset.id;
	const row = manualAssets.find(r => String(r.id) === String(id));
	if (!row) return;
	fillManualForm(row);
	document.getElementById('manualAssetTitle').textContent = 'Manuelles Asset bearbeiten';
	document.getElementById('btnManualAssetDelete').classList.remove('d-none');
	bsCanvas?.show();
});

document.getElementById('btnManualAssetDelete')?.addEventListener('click', async () => {
	const id = Number(document.querySelector('#manualAssetForm [name="id"]').value || 0);
	if (!id) return;
	if (!confirm('Dieses Asset wirklich löschen?')) return;
	const fd = new FormData();
	fd.set('id', String(id));
	fd.set('portfolio_id', String(pid));
	const res = await fetch('/execute/depot/depot_manual_asset_delete.php', { method: 'POST', body: fd });
	const json = await res.json();
	if (!json.success) return alert(json.error || 'Fehler beim Löschen');
	bsCanvas?.hide();
	await loadManualAssets();
});

document.getElementById('manualAssetForm')?.addEventListener('submit', async (ev) => {
	ev.preventDefault();
	const form = ev.currentTarget;
	const fd = new FormData(form);
	const id = Number(fd.get('id') || 0);
	const url = id ? '/execute/depot/depot_manual_asset_update.php' : '/execute/depot/depot_manual_asset_create.php';
	const res = await fetch(url, { method: 'POST', body: fd });
	const json = await res.json();
	if (!json.success) return alert(json.error || 'Fehler beim Speichern');
	bsCanvas?.hide();
	await loadManualAssets();
});

function resetManualForm() {
	const f = document.getElementById('manualAssetForm');
	f.reset();
	f.querySelector('[name="id"]').value = '';
	f.querySelector('[name="currency"]').value = 'EUR';
	}
	
	function fillManualForm(row) {
	const f = document.getElementById('manualAssetForm');
	f.querySelector('[name="id"]').value = row.id;
	f.querySelector('[name="portfolio_id"]').value = pid;
	f.querySelector('[name="label"]').value = row.label || '';
	f.querySelector('[name="category"]').value = row.category || 'Other';
	f.querySelector('[name="value"]').value = row.value || 0;
	f.querySelector('[name="currency"]').value = row.currency || 'EUR';
	f.querySelector('[name="notes"]').value = row.notes || '';
}

function escapeHtml(s) {
	return (s || '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[c]));
}

document.addEventListener('DOMContentLoaded', async () => {
  await (typeof loadManualAssets === 'function' ? loadManualAssets() : null);

  if (!Array.isArray(window.__manual_alloc_rows__) || !window.__manual_alloc_rows__.length) {
	window.__manual_alloc_rows__ = (manualAssets || []).map(r => ({
	  label: r.label, value: Number(r.value) || 0, kind: r.category || 'Other'
	}));
  }

  if (typeof metrics !== 'undefined') {
	window.buildAllocationCharts(metrics, { force: true });
  } else {
	window.buildAllocationCharts({ force: true }); // nutzt window.metrics Fallback
  }
});

})();

</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const nf2 = new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  let sumShares = 0, sumBuyValue = 0, sumUsd = 0;

  document.querySelectorAll('#depotTableSold tbody tr').forEach(tr => {
	const shares = parseFloat(tr.dataset.shares || '0');
	const buyVal = parseFloat(tr.dataset.buy_value || '0');
	const usd    = parseFloat(tr.dataset.realized_usd || '0');

	sumShares   += shares;
	sumBuyValue += buyVal;
	sumUsd      += usd;
  });

  const pct = sumBuyValue > 0 ? (sumUsd / sumBuyValue * 100) : 0;

  const elShares = document.getElementById('soldSumShares');
  const elBuyVal = document.getElementById('soldSumBuyValue');
  const elUsd    = document.getElementById('soldSumUsd');
  const elPct    = document.getElementById('soldSumPct');

  if (elShares) elShares.textContent = nf2.format(sumShares);
  if (elBuyVal) elBuyVal.textContent = nf2.format(sumBuyValue);

  if (elUsd) {
	elUsd.textContent = (sumUsd >= 0 ? '+' : '–') + nf2.format(Math.abs(sumUsd));
	elUsd.classList.add(sumUsd >= 0 ? 'text-success' : 'text-danger');
  }
  if (elPct) {
	elPct.textContent = nf2.format(pct) + ' %';
	elPct.classList.add(pct >= 0 ? 'text-success' : 'text-danger');
  }
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const ctx = document.getElementById('depotPerformanceChart');
  if (!ctx) return;

  fetch('/execute/depot/depot_timeseries.php?pid=<?= (int)$pid ?>')
	.then(response => response.json())
	.then(data => {
	  const START_CAPITAL = parseFloat('<?= number_format($startCapital, 2, ".", "") ?>');
	  const returnsData = data.series.return;

	  // Gesamtrendite (letzter Depotwert - Startkapital)
	  const lastValue = data.series.value[data.series.value.length - 1];
	  const totalReturnAbs = lastValue - START_CAPITAL;
	  const totalReturnPct = START_CAPITAL > 0 ? (totalReturnAbs / START_CAPITAL) * 100 : 0;

	  const nf2 = new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
	  document.getElementById('kpiTotalReturnAbs').textContent = nf2.format(totalReturnAbs);
	  document.getElementById('kpiTotalReturnPct').textContent = nf2.format(totalReturnPct) + ' %';

	  // Min & Max Rendite finden
	  const maxVal = Math.max(...returnsData);
	  const minVal = Math.min(...returnsData);

	  new Chart(ctx, {
		type: 'line',
		data: {
		  labels: data.labels,
		  datasets: [{
			label: 'Rendite (%)',
			data: returnsData,
			borderColor: 'rgba(0,0,0,1)',
			borderWidth: 2.5,
			tension: 0.1,
			fill: false,
			pointRadius: 0,
			pointHoverRadius: 4
		  }]
		},
		options: {
		  responsive: true,
		  maintainAspectRatio:false,
		  interaction: {
			mode: 'nearest',
			axis: 'x',
			intersect: false
		  },
		  plugins: {
			legend: { display: false },
			tooltip: {
			  enabled: true,
			  callbacks: {
				label: ctx => ctx.parsed.y.toFixed(2) + ' %'
			  }
			},
			annotation: {
			  annotations: {
				zeroLine: {
				  type: 'line',
				  yMin: 0,
				  yMax: 0,
				  borderColor: 'rgba(0,0,0,0.6)',
				  borderWidth: 1,
				  borderDash: [5, 5]
				},
				highLine: {
				  type: 'line',
				  yMin: maxVal,
				  yMax: maxVal,
				  borderColor: 'rgba(0,0,0,0.25)',
				  borderWidth: 1,
				  borderDash: [5, 5],
				  label: {
					content: `High: ${maxVal.toFixed(2)}%`,
					enabled: true,
					position: 'center',
					backgroundColor: 'rgba(0,0,0,0.7)',
					color: '#fff'
				  }
				},
				lowLine: {
				  type: 'line',
				  yMin: minVal,
				  yMax: minVal,
				  borderColor: 'rgba(0,0,0,0.25)',
				  borderWidth: 1,
				  borderDash: [5, 5],
				  label: {
					content: `Low: ${minVal.toFixed(2)}%`,
					enabled: true,
					position: 'center',
					backgroundColor: 'rgba(0,0,0,0.7)',
					color: '#fff'
				  }
				}
			  }
			}
		  },
		  scales: {
			x: { display: false, grid: { display: false } },
			y: { display: false, grid: { display: false } }
		  }
		}
	  });
	});
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
	const sparklines = document.querySelectorAll('.sparkline');

	sparklines.forEach(canvas => {
		const symbol = canvas.dataset.symbol;

		fetch(`/execute/depot/depot_entry_chart.php?symbol=${encodeURIComponent(symbol)}&pid=<?= (int)$pid ?>`)
		  .then(res => {
			if (!res.ok) throw new Error(`HTTP ${res.status}`);
			return res.json();
		  })
		  .then(data => {
			// Datenform erkennen
			const values = Array.isArray(data)
			  ? data
			  : (data.values || data.series?.values || data.series || []);
		
			const labels = Array.isArray(data)
			  ? data.map((_, i) => i + 1)
			  : (data.labels || values.map((_, i) => i + 1));
		
			if (!Array.isArray(values) || values.length === 0) return; // nichts zeichnen
		
			new Chart(canvas.getContext('2d'), {
			  type: 'line',
			  data: {
				labels,
				datasets: [{
				  data: values,
				  borderColor: 'black',
				  backgroundColor: 'transparent',
				  borderWidth: 1,
				  tension: 0.2,
				  pointRadius: 0
				}]
			  },
			  options: {
				responsive: true,
				maintainAspectRatio:false,
				plugins: { legend: { display: false }, tooltip: { enabled: false } },
				scales: { x: { display: false }, y: { display: false } }
			  }
			});
		  })
		  .catch(err => {
			console.warn('sparkline load failed for', symbol, err);
		  });
	});
});
</script>
