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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_portfolio'])) {
	$stmt = $pdo->prepare("INSERT INTO portfolios (name) VALUES (?)");
	$stmt->execute([$_POST['new_portfolio']]);
	header("Location: portfolio.php");
	exit;
}

if (isset($_POST['rename_portfolio'])) {
	$stmt = $pdo->prepare("UPDATE portfolios SET name = ? WHERE id = ?");
	$stmt->execute([$_POST['new_name'], $_POST['portfolio_id']]);
	header("Location: portfolio.php");
	exit;
}

if (isset($_POST['delete_portfolio'])) {
	$stmt = $pdo->prepare("DELETE FROM portfolios WHERE id = ?");
	$stmt->execute([$_POST['portfolio_id']]);
	header("Location: portfolio.php");
	exit;
}

if (isset($_POST['add_asset'])) {
	$stmt = $pdo->prepare("INSERT INTO assets (portfolio_id, symbol, amount, asset_class, asset_sector, asset_vola) VALUES (?, ?, ?, ?, ?, ?)");
	$stmt->execute([
		$_POST['portfolio_id'], $_POST['symbol'], $_POST['amount'], $_POST['asset_class'], $_POST['asset_sector'], $_POST['asset_vola']
	]);
	header("Location: portfolio.php");
	exit;
}

if (isset($_POST['edit_asset'])) {
	$stmt = $pdo->prepare("UPDATE assets SET symbol = ?, amount = ?, asset_class = ?, asset_sector = ?, asset_vola = ? WHERE id = ?");
	$stmt->execute([$_POST['symbol'], $_POST['amount'], $_POST['asset_class'], $_POST['asset_sector'], $_POST['asset_vola'], $_POST['asset_id']]);
	header("Location: portfolio.php");
	exit;
}

if (isset($_POST['delete_asset'])) {
	$stmt = $pdo->prepare("DELETE FROM assets WHERE id = ?");
	$stmt->execute([$_POST['asset_id']]);
	header("Location: portfolio.php");
	exit;
}

$portfolios = $pdo->query("SELECT * FROM portfolios")->fetchAll(PDO::FETCH_ASSOC);

?>

<main class="flex-grow-1">
	<section>
		<div class="container my-5">
			<div class="row gx-5">
				<div class="col-lg-12">
					<h1>Portfolios</h1>
					<form method="post" class="mb-4">
						<div class="input-group">
							<input name="new_portfolio" class="form-control" placeholder="Neues Portfolio..." required>
							<button class="btn btn-dark"><i class="fas fa-plus fa-sm"></i> Hinzufügen</button>
						</div>
					</form>
				
					<?php foreach ($portfolios as $portfolio): ?>
						<div class="card mb-4">
							<div class="card-header d-flex justify-content-between align-items-center">
								<form method="post" class="d-flex gap-2">
									<input type="text" name="new_name" class="form-control" value="<?= htmlspecialchars($portfolio['name']) ?>">
									<input type="hidden" name="portfolio_id" value="<?= $portfolio['id'] ?>">
									<button name="rename_portfolio" class="btn btn-sm btn-outline-dark">Umbenennen</button>
								</form>
								<form method="post">
									<input type="hidden" name="portfolio_id" value="<?= $portfolio['id'] ?>">
									<button name="delete_portfolio" class="btn btn-sm btn-outline-danger" onclick="return confirm('Portfolio wirklich löschen?')"><i class="fas fa-trash fa-sm"></i> Löschen</button>
								</form>
							</div>
							<div class="card-body row">
								<div class="col-md-6">
									<?php
									$assets = $pdo->prepare("SELECT * FROM assets WHERE portfolio_id = ?");
									$assets->execute([$portfolio['id']]);
									$asset_list = $assets->fetchAll(PDO::FETCH_ASSOC);
									$asset_count = count($asset_list);
									$totalAmount = array_sum(array_column($asset_list, 'amount'));
									?>
									
									<h5>Werte <span class="badge text-bg-secondary"><?= $asset_count ?></span></h5>
									<form method="post" class="row g-2 mb-3">
										<input type="hidden" name="portfolio_id" value="<?= $portfolio['id'] ?>">
										<div class="col-4">
											<input name="symbol" class="form-control form-control-sm" placeholder="Symbol" required>
										</div>
										<div class="col-4">
											<input name="amount" type="number" step="0.01" class="form-control form-control-sm" placeholder="Betrag (€)" required>
										</div>
										<div class="col-4">
											<input name="asset_class" class="form-control form-control-sm" placeholder="Assetklasse" required>
										</div>
										<div class="col-4">
											<input name="asset_sector" class="form-control form-control-sm" placeholder="Sektor" required>
										</div>
										<div class="col-4">
											<input name="asset_vola" class="form-control form-control-sm" placeholder="Vola (%)" required>
										</div>
										<div class="col-4">
											<button name="add_asset" class="btn btn-sm btn-dark btn-block"><i class="fas fa-plus fa-sm"></i> Hinzufügen</button>
										</div>
									</form>
									
									<?php foreach ($asset_list as $asset): ?>
										<?php								
										if ($totalAmount > 0) {
											$anteil = $asset['amount'] / $totalAmount;
											$anteilige_vola = $anteil * ($asset['asset_vola'] / 100);
										} 
										?>
										<div class="rounded d-flex justify-content-between align-items-center bg-light p-3 mb-1">
											<form method="post" class="row g-2">
												<div class="col-12 d-flex justify-content-between">
													<?= "<small><strong>{$asset['symbol']}</strong><span class='badge text-bg-warning rounded-pill text-white ms-2'>" . round($anteil * 100, 2) . "%</span></small><small>Vola: {$asset['asset_vola']}% (anteilig: " . round($anteilige_vola * 100, 2) . "%)</small>"; ?>
												</div>
												<div class="col-4">
													<input name="symbol" value="<?= htmlspecialchars($asset['symbol']) ?>" class="form-control form-control-sm" required>
												</div>
												<div class="col-4">
													<input name="amount" type="number" step="0.01" value="<?= $asset['amount'] ?>" class="form-control form-control-sm" required>
												</div>
												<div class="col-4">
													<input name="asset_class" value="<?= htmlspecialchars($asset['asset_class']) ?>" class="form-control form-control-sm" required>
												</div>
												<div class="col-4">
													<input name="asset_sector" value="<?= htmlspecialchars($asset['asset_sector']) ?>" class="form-control form-control-sm" required>
												</div>
												<div class="col-4">
													<input name="asset_vola" value="<?= htmlspecialchars($asset['asset_vola']) ?>" class="form-control form-control-sm" required>
												</div>
												<div class="col-12 mt-2">
													<input type="hidden" name="asset_id" value="<?= $asset['id'] ?>">
													<button name="edit_asset" class="btn btn-sm btn-outline-dark">Speichern</button>
												</div>
											</form>
											<form method="post" class="ms-2">
												<input type="hidden" name="asset_id" value="<?= $asset['id'] ?>">
												<button name="delete_asset" class="btn btn-sm btn-outline-danger" onclick="return confirm('Wert löschen?')"><i class="fas fa-trash fa-sm"></i></button>
											</form>
										</div>
									<?php endforeach; ?>
								</div>
								<div class="col-md-6">
									<p class="text-center mt-3 mb-1"><?= htmlspecialchars($portfolio['name']) ?></p>
									<h2 class="fw-bold text-center mb-4">Gesamtwert: € <?= number_format($totalAmount, 2, ',', '.') ?></h2>
									<canvas id="chart-<?= $portfolio['id'] ?>"></canvas>
									<div class="my-4 text-center">
										<div class="badge text-bg-dark text-white">
											Durchschnittliche anteilige Volatilität: 
											<?php
											$gesamt_anteilige_vola = 0.0;
											$totalAmountMitVola = 0.0;
											
											// Berechne nur den Gesamtwert der Assets mit Volatilität > 0
											foreach ($asset_list as $asset) {
												if (is_numeric($asset['asset_vola']) && floatval($asset['asset_vola']) > 0) {
													$totalAmountMitVola += $asset['amount'];
												}
											}
											
											foreach ($asset_list as $asset) {
												if (is_numeric($asset['asset_vola']) && floatval($asset['asset_vola']) > 0) {													
													$anteil = $asset['amount'] / $totalAmountMitVola;
													$anteilige_vola = $anteil * (floatval($asset['asset_vola']) / 100);
													$gesamt_anteilige_vola += $anteilige_vola;
												}
											}
											
											echo round($gesamt_anteilige_vola * 100, 2) . "% / Monat";
											?>
										</div>
									</div>
									<div class="mt-4">
										<h6 class="fw-bold text-center mt-4">Assetklassen</h6>
										<canvas id="barchart-<?= $portfolio['id'] ?>" width="400" height="200"></canvas>
									</div>
									<div class="mt-4">
										<h6 class="fw-bold text-center">Sektoren</h6>
										<canvas id="barchart-<?= $portfolio['id'] ?>-sectors" width="400" height="200"></canvas>
									</div>
									<div class="mt-4">
										<h6 class="fw-bold text-center">Assets</h6>
										<canvas id="bar-<?= $portfolio['id'] ?>" style="width: 100%; height: 600px;"></canvas>
									</div>
									
									<?php
									$symbols = [];
									
									foreach ($asset_list as $asset) {
										if (!empty($asset['symbol'])) {
											$symbols[$asset['symbol']] = ($symbols[$asset['symbol']] ?? 0) + $asset['amount'];
										}
										if (!empty($asset['asset_sector'])) {
											$sectors[$asset['asset_sector']] = ($sectors[$asset['asset_sector']] ?? 0) + $asset['amount'];
										}
									}
									
									arsort($symbols);
									arsort($sectors);
									?>
									
									<!-- Assetklassen -->
									<script>
										const ctx<?= $portfolio['id'] ?> = document.getElementById('chart-<?= $portfolio['id'] ?>');
										new Chart(ctx<?= $portfolio['id'] ?>, {
											type: 'pie',
											data: {
												labels: <?= json_encode(array_values(array_unique(array_filter(array_column($asset_list, 'asset_class'))))) ?>,
												datasets: [{
													data: <?= json_encode(array_values(array_reduce($asset_list, function ($acc, $a) {
														$acc[$a['asset_class']] = ($acc[$a['asset_class']] ?? 0) + $a['amount'];
														return $acc;
													}, []))) ?>,
													backgroundColor: [
														'#4A90E2', '#7ED321', '#F66D6D', '#F5A623', '#50E3C2', '#9013FE', '#4A4A4A', '#FF7BAC', '#00A8A8', '#D4A76A', '#1ABC9C', '#2ECC71', '#3498DB', '#9B59B6', '#34495E', '#16A085', '#27AE60', '#2980B9', '#8E44AD', '#2C3E50', '#E67E22', '#E74C3C', '#ECF0F1', '#95A5A6', '#F39C12', '#D35400', '#C0392B', '#BDC3C7', '#7F8C8D', '#FF6F61', '#6B5B95', '#88B04B', '#F7CAC9', '#92A8D1', '#955251', '#B565A7', '#009B77', '#DD4124', '#45B8AC', '#EFC050'
													]
												}]
											},
											options: {
												plugins: {
													legend: {
														display: true,
														position: 'top'
													},
													datalabels: {
														formatter: (value, context) => {
															const data = context.chart.data.datasets[0].data;
															const labels = context.chart.data.labels;
															const total = data.reduce((sum, val) => sum + val, 0);
															const percent = total ? ((value / total) * 100).toFixed(1) : "0.0";
															const label = labels[context.dataIndex];
															return `${label}: ${percent}%`;
														},
														color: '#fff',
														font: { weight: 'bold' }
													}
												}
											},
											plugins: [ChartDataLabels]
										});
									</script>
									
									<!-- Sectors -->
									<script>
									const sectorCtx<?= $portfolio['id'] ?> = document.getElementById('barchart-<?= $portfolio['id'] ?>-sectors');
									new Chart(sectorCtx<?= $portfolio['id'] ?>, {
										type: 'bar',
										data: {
											labels: <?= json_encode(array_keys($sectors)) ?>,
											datasets: [{
												label: 'Betrag (€)',
												data: <?= json_encode(array_values($sectors)) ?>,
												backgroundColor: 'rgba(54, 162, 235, 0.7)',
												borderColor: 'rgba(54, 162, 235, 1)',
												borderWidth: 1
											}]
										},
										options: {
											responsive: true,
											plugins: {
												legend: { display: false },
												tooltip: { enabled: true }
											},
											scales: {
												y: { beginAtZero: true }
											}
										}
									});
									</script>
									<script>
										const rawData<?= $portfolio['id'] ?> = <?= json_encode(array_reduce($asset_list, function ($acc, $a) {
											$acc[$a['asset_class']] = ($acc[$a['asset_class']] ?? 0) + $a['amount'];
											return $acc;
										}, [])) ?>;
									
										const entries<?= $portfolio['id'] ?> = Object.entries(rawData<?= $portfolio['id'] ?>);
									
										// Berechnung und Sortierung
										const sortedData<?= $portfolio['id'] ?> = entries<?= $portfolio['id'] ?>
											.map(([label, value]) => ({ label, value }))
											.sort((a, b) => b.value - a.value);
									
										const total<?= $portfolio['id'] ?> = sortedData<?= $portfolio['id'] ?>.reduce((sum, item) => sum + item.value, 0);
									
										const bctx<?= $portfolio['id'] ?> = document.getElementById('barchart-<?= $portfolio['id'] ?>');
										new Chart(bctx<?= $portfolio['id'] ?>, {
											type: 'bar',
											data: {
												labels: sortedData<?= $portfolio['id'] ?>.map(e => e.label),
												datasets: [{
													label: 'Summe pro Assetklasse (€)',
													data: sortedData<?= $portfolio['id'] ?>.map(e => e.value),
													backgroundColor: 'rgba(54, 162, 235, 0.7)',
													borderColor: 'rgba(54, 162, 235, 1)',
													borderWidth: 1
												}]
											},
											options: {
												scales: {
													y: {
														beginAtZero: true,
														ticks: {
															callback: value => value.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })
														}
													}
												},
												plugins: {
													legend: { display: false },
													tooltip: {
														callbacks: {
															label: function(ctx) {
																const value = ctx.parsed.y;
																const percent = total<?= $portfolio['id'] ?> > 0 ? ((value / total<?= $portfolio['id'] ?>) * 100).toFixed(1) : 0;
																return `${value.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })} (${percent}%)`;
															}
														}
													}
												}
											}
										});
									</script>
									
									<!-- Assets -->
									<script>
										const barCtx<?= $portfolio['id'] ?> = document.getElementById('bar-<?= $portfolio['id'] ?>');
										const rawLabels = <?= json_encode(array_keys($symbols)) ?>;
										const rawData = <?= json_encode(array_values($symbols)) ?>;
									
										// Kombiniere und sortiere nach Wert absteigend
										const combined = rawLabels.map((label, i) => ({ label, value: rawData[i] }));
										combined.sort((a, b) => b.value - a.value);
									
										const sortedLabels = combined.map(item => item.label);
										const sortedData = combined.map(item => item.value);
									
										new Chart(barCtx<?= $portfolio['id'] ?>, {
											type: 'bar',
											data: {
												labels: sortedLabels,
												datasets: [{
													label: 'Betrag (€)',
													data: sortedData,
													backgroundColor: 'rgba(54, 162, 235, 0.7)',
													borderColor: 'rgba(54, 162, 235, 1)',
													borderWidth: 1
												}]
											},
											options: {
												indexAxis: 'y',
												responsive: true,
												plugins: {
													legend: { display: false },
													tooltip: {
														callbacks: {
															label: ctx => `€ ${ctx.raw.toLocaleString('de-DE', { minimumFractionDigits: 2 })}`
														}
													}
												},
												scales: {
													x: {
														beginAtZero: true,
														title: { display: true, text: 'Betrag (€)' }
													},
													y: {
														title: { display: false }
													}
												}
											}
										});
									</script>
									
								</div>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
			</div>
		</div>
	</section>
</main>
<?php require_once __DIR__ . '/views/footer.php'; ?>