<?php require_once __DIR__ . '/engine/engine.php'; ?>
<?php require_once __DIR__ . '/engine/api-handling/api_helpers.php'; ?>
<?php $requires_search = true; ?>
<?php $requires_chartjs = true; ?>
<?php require_once __DIR__ . '/views/header.php'; ?>
<?php require_once __DIR__ . '/views/navigation.php'; ?>

<?php

require_once 'execute/dashboard/indicators.php';

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

$indicator_groups = [
    'Vorlaufindikatoren' => ['NFCI','ISM', 'UMCSENT', 'PERMIT', 'NFIB', 'DCOILWTICO', 'PCOPPUSDM', 'PIORECRUSDM', 'BAMLC0A1CAAAEY', 'BAMLC0A4CBBBEY', 'BAMLH0A3HYC', 'M2SL', 'T10Y2Y', 'BAMLH0A0HYM2'],
    'IST-Indikatoren' => ['INDPRO', 'FEDFUNDS'],
    'Nachlauf-Indikatoren' => ['USGDPQQ', 'CPALTT01USM657N'],
    'FED-Mandate' => ['UNRATE', 'USGDPQQ', 'CPALTT01USM657N'],
    'Zyklische Rohstoffe' => ['DCOILWTICO', 'PCOPPUSDM', 'PIORECRUSDM'],
    'Konjunkturzyklus' => ['ISM', 'USGDPQQ', 'UMCSENT', 'UNRATE', 'RETAILMPCSMSA', 'INDPRO', 'PERMIT', 'MORTGAGE30US', 'ACDGNO'],
    'Inflation & Geldpolitik' => ['CPALTT01USM657N', 'FEDFUNDS', 'T10Y2Y', 'M2SL', 'BAMLC0A1CAAAEY', 'BAMLC0A4CBBBEY', 'BAMLH0A3HYC'],
    'Liquidität & Kreditvergabe' => ['M2SL', 'BAMLC0A1CAAAEY', 'BAMLC0A4CBBBEY', 'BAMLH0A3HYC'],
    'Sentiment' => ['UMCSENT', 'NFIB'],
    'Bewertung Assetklassen' => ['SHILLER', 'BUFFET', 'ACDGNO']
];

$stmt = $pdo->query("SELECT COUNT(*) FROM macro_indicators");
$count = $stmt->fetchColumn();
if ($count == 0) {
    $stmt = $pdo->prepare("INSERT INTO macro_indicators (name, value, threshold, trend) VALUES (?, ?, ?, ?)");
    foreach ($indicators as $key => $meta) {
        $stmt->execute([$key, 0, $meta['threshold'], 'steigend']);
    }
}

$stmt = $pdo->query("SELECT name, value, threshold, trend, created_at FROM macro_indicators ORDER BY name ASC");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$data = [];

foreach ($indicators as $name => $meta) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM macro_indicators WHERE name = ?");
    $stmt->execute([$name]);
    $exists = $stmt->fetchColumn();
    
    if (!$exists) {
        $stmt = $pdo->prepare("INSERT INTO macro_indicators (name, value, threshold, trend, created_at) VALUES (:name, 0, 0, 'seitwärts', NOW())");
        $stmt->execute(['name' => $name]);
    }
}

foreach ($rows as $row) {
    $data[$row['name']] = $row;
}

function scoreIndicator($value, $threshold, $trend, $invert = false) {
    $score = 0;

    $isCritical = $invert ? ($value > $threshold) : ($value < $threshold);
    $score = $isCritical ? -1 : +1;

    if ($trend === 'fallend') {
        $score += $invert ? +0.5 : -0.5;
    } elseif ($trend === 'steigend') {
        $score += $invert ? -0.5 : +0.5;
    }

    return max(-1.5, min(1.5, $score));
}
$totalScore = 0;
$totalWeight = 0;

foreach ($indicators as $key => $meta) {
    if (!isset($data[$key])) continue;

    $value = $data[$key]['value'] ?? null;
    $trend = $data[$key]['trend'] ?? 'seitwärts';
    $threshold = $meta['threshold'] ?? null;
    $invert = $meta['invert'] ?? false;

    if ($value === null || $threshold === null) continue;

    $score = scoreIndicator($value, $threshold, $trend, $invert);
    $weight = 1;

    $totalScore += $score * $weight;
    $totalWeight += $weight;
}

$finalScore = $totalWeight > 0 ? round($totalScore / $totalWeight, 2) : 0;

if ($finalScore >= 1.0) {
    $summary = "Sehr positiv";
    $color = "success";
} elseif ($finalScore >= 0.5) {
    $summary = "Positiv";
    $color = "primary";
} elseif ($finalScore >= -0.5) {
    $summary = "Neutral";
    $color = "warning";
} elseif ($finalScore >= -1.0) {
    $summary = "Negativ";
    $color = "danger";
} else {
    $summary = "Sehr negativ";
    $color = "dark";
}

$stmt = $pdo->query("SELECT score FROM macro_score_history ORDER BY created_at DESC LIMIT 1");
$lastScore = $stmt->fetchColumn();

if (!is_numeric($lastScore) || round((float)$lastScore, 2) !== round((float)$finalScore, 2)) {
    $stmt = $pdo->prepare("INSERT INTO macro_score_history (score, phase, interpretation) VALUES (?, ?, ?)");
    $stmt->execute([$finalScore, $phase ?? '', $summary]);
}

$scoreData = $pdo->query("SELECT DATE(created_at) AS date, score FROM macro_score_history ORDER BY created_at ASC")->fetchAll(PDO::FETCH_ASSOC);
$chartLabels = json_encode(array_column($scoreData, 'date'));
$chartScores = json_encode(array_column($scoreData, 'score'));
$chartPhases = json_encode(array_column($scoreData, 'phase'));
$chartInterpretations = json_encode(array_column($scoreData, 'interpretation'));

$deltas = [];
for ($i = 0; $i < count($scoreData); $i++) {
    if ($i === 0) {
        $deltas[] = 0;
    } else {
        $prev = (float)$scoreData[$i - 1]['score'];
        $curr = (float)$scoreData[$i]['score'];
        $delta = round($curr - $prev, 2);
        $deltas[] = $delta;
    }
}
$chartDeltas = json_encode($deltas);
?>

<main class="flex-grow-1">
  
  <section class="mt-5">
    <div class="container">
      <?php
        $ism = $data['ISM']['value'] ?? 0;
        $ism_trend = $data['ISM']['trend'] ?? 'seitwärts';
        $cpi = $data['CPALTT01USM657N']['value'] ?? 0;
        $cpi_trend = $data['CPALTT01USM657N']['trend'] ?? 'seitwärts';
        
        $ism_threshold = 50;
        $cpi_threshold = 2.0;
        
        $expansion = $ism >= $ism_threshold;
        $inflation_high = $cpi >= $cpi_threshold;
        $inflation_rising = $cpi_trend == 'steigend';
        
        if ($expansion && !$inflation_high && !$inflation_rising) {
            $phase = 'FRÜHLING';
        } elseif ($expansion && ($inflation_high || $inflation_rising)) {
            $phase = 'SOMMER';
        } elseif (!$expansion && $inflation_high) {
            $phase = 'HERBST';
        } else {
            $phase = 'WINTER';
        }
        
        if ($finalScore >= 1.0) {
            $summary = "Sehr positiv";
        } elseif ($finalScore >= 0.5) {
            $summary = "Positiv";
        } elseif ($finalScore >= -0.5) {
            $summary = "Neutral bis leicht negativ";
        } elseif ($finalScore >= -1.0) {
            $summary = "Deutlich negativ";
        } else {
            $summary = "Kritisch";
        }
      ?>
      <div class="row gx-2">
        <div class="col-lg-6">
          <div class="card">
            <div class="card-body">
              <h5>Makrophase:</h5>
              <h5><span class="text-white badge bg-dark"><?= $phase ?></span></h5>
              Basiert auf <strong>ISM <?= $ism ?></strong> (<?= $ism_trend ?>), <strong>CPI <?= $cpi ?> %</strong> (<?= $cpi_trend ?>)
            </div>
          </div>
          <div class="card mt-2">
            <div class="card-body">
              <h5>Makro-Score:</h5>
              <h5><span class="text-white badge bg-<?= $color ?>"><?= $finalScore ?></span></h5>
              Bewertung: <strong><?= $summary ?></strong>
            </div>
          </div>
        </div>
        <div class="col-lg-6">
          <div class="card">
            <div class="card-body">
              <h5>Makro-Score Verlauf:</h5>
              <canvas id="macroScoreChart" height="94"></canvas>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
  
  <section class="mt-4 mb-5">
    <div class="container">
      <div class="sticky-top mt-2 bg-white z-3 pt-3 sticky-offset">
        <div class="row">
          <div class="col-lg-6">
            <h2 class="mb-3">Makro-Dashboard</h2>
          </div>
          <div class="col-lg-6 d-flex align-items-top justify-content-start justify-content-lg-end">
            <form method="get" class="d-inline-block me-2">
              <select id="groupFilter" name="group" class="form-select" onchange="this.form.submit()">
                <option value="">Alle</option>
                <?php foreach ($indicator_groups as $group => $ids): ?>
                  <option value="<?= htmlspecialchars($group) ?>" <?= ($_GET['group'] ?? '') === $group ? 'selected' : '' ?>>
                    <?= htmlspecialchars($group) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </form>
            <a href="execute/dashboard/fetch_fred_data.php" class="btn btn-outline-secondary mb-3">
              <i class="fas fa-rotate"></i> FRED-Sync
            </a>
          </div>
        </div>
      </div>
    
      <form action="execute/dashboard/save_indicators.php" method="POST" class="row g-3 mb-4">
        <?php
        $activeGroup = $_GET['group'] ?? '';
        $activeIds = $activeGroup && isset($indicator_groups[$activeGroup])
            ? $indicator_groups[$activeGroup]
            : array_keys($indicators);
        ?>
        
        <?php foreach ($activeIds as $key): ?>
          <?php
            if (!isset($indicators[$key])) continue;
            
            $meta = $indicators[$key];
            $label = $meta['label'] ?? '';
            $description = $meta['description'] ?? '';
            $threshold = $meta['threshold'] ?? '';
            $url = $meta['url'] ?? '';
            $value = $data[$key]['value'] ?? '';
            $invert = $meta['invert'] ?? false;
            $threshold = $meta['threshold'] ?? '';
            $value = $data[$key]['value'] ?? '';
      
            if ($threshold !== '' && $value !== '') {
                if ($invert) {
                    $isCritical = ($value > $threshold);
                } else {
                    $isCritical = ($value < $threshold);
                }
                $borderClass = $isCritical ? 'border-danger bg-danger' : 'border-success bg-success';
                $color = $isCritical ? 'danger' : 'success';
            } else {
                $borderClass = 'border-secondary';
                $color = 'secondary';
            }
          ?>
          <div class="col-lg-6 col-xl-4">
            <div class="card macro-card <?= $borderClass ?> bg-opacity-10">
              <div class="card-body">
                <h5 class="card-title d-flex justify-content-between">
                  <?php
                  $trend = $data[$key]['trend'] ?? 'steigend';
                  switch ($trend) {
                      case 'steigend':
                          $icon = 'fa-arrow-trend-up text-dark';
                          break;
                      case 'fallend':
                          $icon = 'fa-arrow-trend-down text-dark';
                          break;
                      case 'seitwärts':
                      default:
                          $icon = 'fa-arrows-left-right text-dark';
                          break;
                  }
                  ?>
                  <div>
                    <a href="<?php echo $url; ?>" target="_blank" class="text-decoration-none text-dark d-block mb-1">
                      <i class="fa fa-circle-chevron-right fa-xs"></i> <?php echo htmlspecialchars($label); ?>
                    </a>
                    <p class="fs-small mb-0"><?php echo htmlspecialchars($description); ?></p>
                  </div>
                  <i class='fas <?php echo $icon; ?>'></i>
                </h5>
                <div class="row gx-2">
                  <div class="col-sm-6">
                    <input type="number" step="0.01" min="-100000" class="form-control mb-2 d-block" name="<?php echo $key; ?>" value="<?php echo $value; ?>" required>
                  </div>
                  <div class="col-sm-6">
                    <select name="<?php echo $key; ?>_trend" class="form-select form-select mb-2 d-block">
                      <option value="steigend" <?php echo (($data[$key]['trend'] ?? '') === 'steigend') ? 'selected' : ''; ?>>steigend</option>
                      <option value="fallend" <?php echo (($data[$key]['trend'] ?? '') === 'fallend') ? 'selected' : ''; ?>>fallend</option>
                      <option value="seitwärts" <?php echo (($data[$key]['trend'] ?? '') === 'seitwärts') ? 'selected' : ''; ?>>seitwärts</option>
                    </select>
                  </div>
                </div>
                <div class="d-flex justify-content-between">
                  <div>
                    <p class="mb-0 text-muted">Schwelle: <?php echo $threshold; ?></p>
                    <h4 class="text-<?php echo $color; ?> mb-0"><?php echo $value; ?></h4>
                  </div>
                  <div>
                    <?php if (in_array($key, $fredKeys)): ?>
                      <img src="assets/img/FRED_Logo_Header.svg" width="60">
                    <?php else: ?>
                      <i class="fas fa-triangle-exclamation fa-lg text-warning"></i>
                    <?php endif; ?>
                  </div>
                </div>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
        <div class="col-12">
          <button type="submit" class="btn btn-dark">Werte aktualisieren</button>
        </div>
      </form>
    </div>
  </section>
  
  <script>
    const ctx = document.getElementById('macroScoreChart').getContext('2d');
  
    const labels = <?= $chartLabels ?>;
    const scores = <?= $chartScores ?>;
    const phases = <?= $chartPhases ?>;
    const interpretations = <?= $chartInterpretations ?>;
    const deltas = <?= $chartDeltas ?>;
  
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
          label: 'Makro-Score',
          data: scores,
          borderWidth: 2,
          pointRadius: 3,
          fill: true,
          tension: 0.3,
          backgroundColor: 'rgba(0, 123, 255, 0.1)',
          borderColor: 'rgba(0, 123, 255, 1)'
        }]
      },
      options: {
        responsive: true,
        scales: {
          y: {
            min: -1.5,
            max: 1.5,
            title: {
              display: true,
              text: 'Makro-Score'
            }
          }
        },
        plugins: {
          legend: { display: false },
          tooltip: {
            callbacks: {
              label: function(context) {
                const index = context.dataIndex;
                const score = context.parsed.y;
                const phase = phases[index] || '-';
                const interpretation = interpretations[index] || '-';
                const delta = deltas[index] || 0;
                const deltaStr = delta > 0 ? `+${delta}` : `${delta}`;
                
                return [
                  `Score: ${score}`,
                  `Delta: ${deltaStr}`,
                  `Makrophase: ${phase}`,
                  `Einschätzung: ${interpretation}`
                ];
              }
            }
          },
          annotation: {
            annotations: {
              greenZone: {
                type: 'box',
                yMin: 0.5,
                yMax: 1.5,
                backgroundColor: 'rgba(40, 167, 69, 0.05)',
                borderWidth: 0
              },
              yellowZone: {
                type: 'box',
                yMin: -0.5,
                yMax: 0.5,
                backgroundColor: 'rgba(255, 193, 7, 0.05)',
                borderWidth: 0
              },
              redZone: {
                type: 'box',
                yMin: -1.5,
                yMax: -0.5,
                backgroundColor: 'rgba(220, 53, 69, 0.05)',
                borderWidth: 0
              }
            }
          }
        }
      },
      plugins: [Chart.registry.getPlugin('annotation')]
    });
  </script>
  
</main>
<?php require_once __DIR__ . '/views/footer.php'; ?>