<?php
require_once __DIR__ . '/../../engine/engine.php';
require_once __DIR__ . '/../../engine/api-handling/fmp_client.php';

$symbol = $_GET['symbol'] ?? '';

if (!$symbol) {
    http_response_code(400);
    echo json_encode([]);
    exit;
}

// Multi-Request statt direkter URL
$resp = fmp_multi([
    'hist' => [
        'key'   => 'historical_price_full',
        'vars'  => ['symbol' => strtoupper(trim($symbol))],
        'query' => [
            'serietype'  => 'line',
            'timeseries' => 252
        ]
    ]
], 4);

// Ergebnis entpacken
$data = $resp['hist'] ?? [];
if (is_string($data)) {
    $tmp = json_decode($data, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        $data = $tmp;
    }
}
if (is_object($data)) {
    $data = json_decode(json_encode($data), true);
}
if (isset($data['body'])) $data = $data['body'];
if (isset($data['data'])) $data = $data['data'];

if (!isset($data['historical']) || empty($data['historical'])) {
    echo json_encode([
        'error'             => 'Keine historischen Daten',
        'debug_url'         => 'FMP via fmp_multi',
        'response_snippet'  => substr(json_encode($data), 0, 500) // zur Analyse
    ]);
    exit;
}

$values = array_column($data['historical'], 'close');
$labels = array_column($data['historical'], 'date');

// Aktueller Kurs + Tagesveränderung
$latest          = $values[0] ?? 0;
$previous        = $values[1] ?? 0;
$change          = $latest - $previous;
$change_percent  = $previous != 0 ? ($change / $previous * 100) : 0;

echo json_encode([
    'price'           => $latest,
    'change'          => $change,
    'change_percent'  => $change_percent,
    'values'          => array_reverse($values),
    'labels'          => array_reverse($labels)
]);
