<?php
include 'includes/db.php';
session_start();

$user_id = $_SESSION['user_id'];

$stmt = $conn->prepare("
  SELECT k.bezeichnung,
         ROUND(SUM(TIMESTAMPDIFF(SECOND, z.startzeit, z.endzeit))/3600, 2) AS stunden
  FROM zeiterfassung z
  JOIN kostenstellen k ON k.id = z.kostenstelle_id
  WHERE z.kamerad_id = ? AND z.endzeit IS NOT NULL
  GROUP BY z.kostenstelle_id
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

$labels = [];
$werte = [];

while ($r = $res->fetch_assoc()) {
    $labels[] = $r['bezeichnung'];
    $werte[] = $r['stunden'];
}
?>

<div class="container my-5">
  <h2 class="mb-4">🧾 Zeit nach Kostenstelle</h2>
  <canvas id="ksChart" height="100"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('ksChart').getContext('2d');
new Chart(ctx, {
  type: 'bar',
  data: {
    labels: <?= json_encode($labels) ?>,
    datasets: [{
      label: 'Stunden',
      data: <?= json_encode($werte) ?>,
      backgroundColor: 'rgba(0,123,255,0.5)',
      borderColor: 'rgba(0,123,255,1)',
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      y: { beginAtZero: true, title: { display: true, text: 'Stunden' } },
      x: { title: { display: true, text: 'Kostenstelle' } }
    }
  }
});
</script>
