<?php
require_once __DIR__ . '/../../engine/engine.php';

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

$stmt = $pdo->prepare("
	SELECT snapshot_date, total_value 
	FROM depot_performance 
	WHERE portfolio_id = :pid
	ORDER BY snapshot_date
");
$stmt->execute([':pid' => $pid]);
$data = $stmt->fetchAll();

$labels = [];
$values = [];
$cash = [];
$drawdowns = [];
$returns = [];

$max_so_far = 0;
$first_value = null;

foreach ($data as $row) {
	$labels[] = $row['snapshot_date'];
	$value = (float)$row['total_value'];
	$values[] = $value;

	$barCash = $pdo->prepare("
		SELECT amount 
		FROM depot_cash 
		WHERE portfolio_id = :pid
		ORDER BY id DESC 
		LIMIT 1
	");
	$barCash->execute([':pid' => $pid]);
	$cashValue = $barCash->fetchColumn() ?? 0.0;
	$cash[] = $cashValue;

	$max_so_far = max($max_so_far, $value);
	$dd = $max_so_far > 0 ? ($value - $max_so_far) : 0;
	$drawdowns[] = round($dd, 2);

	if ($first_value === null) {
		$first_value = $value;
	}
	$return = $first_value > 0 ? (($value / $first_value) - 1) * 100 : 0;
	$returns[] = round($return, 2);
}

echo json_encode([
	'labels' => $labels,
	'values' => $values,
	'cash' => $cash,
	'drawdowns' => $drawdowns,
	'returns' => $returns
]);