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

function fetchFredValue($series_id, $FredApiKey) {
    $url = "https://api.stlouisfed.org/fred/series/observations?series_id={$series_id}&api_key={$FredApiKey}&file_type=json&sort_order=desc&limit=1";
    $json = @file_get_contents($url);
    if ($json === false) return null;
    $data = json_decode($json, true);
    if (!isset($data['observations'][0]['value'])) return null;
    $value = $data['observations'][0]['value'];
    return is_numeric($value) ? (float)$value : null;
}

function fetchCpiYoYChange($FredApiKey) {
    $series_id = 'CPIAUCSL';
    $one_year_ago = date('Y-m-01', strtotime('-1 year'));

    $url = "https://api.stlouisfed.org/fred/series/observations?series_id={$series_id}&api_key={$FredApiKey}&file_type=json&observation_start={$one_year_ago}";
    $json = @file_get_contents($url);
    if ($json === false) return null;

    $data = json_decode($json, true);
    $observations = $data['observations'];

    $start_value = null;
    $end_value = null;

    foreach ($observations as $obs) {
        $date = $obs['date'];
        $value = (float)$obs['value'];

        if (substr($date, 0, 7) == substr($one_year_ago, 0, 7)) {
            $start_value = $value;
        }

        $end_value = $value;
    }

    if ($start_value && $end_value) {
        $change = (($end_value - $start_value) / $start_value) * 100;
        return round($change, 2);
    }

    return null;
}

$fredSeries = [
    'UNRATE' => 'UNRATE',
    'FEDFUNDS' => 'FEDFUNDS',
    'UMCSENT' => 'UMCSENT',
    'PERMIT' => 'PERMIT',
    'ACDGNO' => 'ACDGNO',
    'MORTGAGE30US' => 'MORTGAGE30US',
    'BAMLC0A1CAAAEY' => 'BAMLC0A1CAAAEY',
    'BAMLC0A4CBBBEY' => 'BAMLC0A4CBBBEY',
    'BAMLH0A3HYC' => 'BAMLH0A3HYC',
    'M2SL' => 'M2SL',
    'T10Y2Y' => 'T10Y2Y',
    'RETAILMPCSMSA' => 'RETAILMPCSMSA',
    'INDPRO' => 'INDPRO',
    'USGDPQQ' => 'A191RL1Q225SBEA',
    'CPALTT01USM657N' => 'CPALTT01USM657N',
    'DCOILWTICO' => 'DCOILWTICO',
    'PCOPPUSDM' => 'PCOPPUSDM',
    'PIORECRUSDM' => 'PIORECRUSDM',
    'NFCI' => 'NFCI',
    'ICSA' => 'ICSA',
    'BAMLH0A0HYM2' => 'BAMLH0A0HYM2'
];

foreach ($fredSeries as $key => $series_id) {
    $value = fetchFredValue($series_id, $FredApiKey);
    if ($value !== null) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM macro_indicators WHERE name = ?");
        $stmt->execute([$key]);
        $exists = $stmt->fetchColumn();

        if ($exists) {
            $stmt = $pdo->prepare("UPDATE macro_indicators SET value = ?, created_at = CURRENT_TIMESTAMP WHERE name = ?");
            $stmt->execute([$value, $key]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO macro_indicators (name, value, threshold, trend, created_at) VALUES (?, ?, 0, 'seitwärts', CURRENT_TIMESTAMP)");
            $stmt->execute([$key, $value]);
        }
    }
}

$key = 'CPALTT01USM657N';
$value = fetchCpiYoYChange($FredApiKey);
if ($value !== null) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM macro_indicators WHERE name = ?");
    $stmt->execute([$key]);
    $exists = $stmt->fetchColumn();

    if ($exists) {
        $stmt = $pdo->prepare("UPDATE macro_indicators SET value = ?, created_at = CURRENT_TIMESTAMP WHERE name = ?");
        $stmt->execute([$value, $key]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO macro_indicators (name, value, threshold, trend, created_at) VALUES (?, ?, 0, 'seitwärts', CURRENT_TIMESTAMP)");
        $stmt->execute([$key, $value]);
    }
}

header("Location: ../../index.php");
exit;
?>
