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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$einheit = $_SESSION['einheit'] ?? '';

// Monat/Jahr Filter
$monat = $_GET['monat'] ?? date('m');
$jahr = $_GET['jahr'] ?? date('Y');

// Start/Ende für SQL
$startdatum = "$jahr-$monat-01";
$enddatum = date("Y-m-t", strtotime($startdatum));

// Alle Benutzer in deiner Einheit + Zeit im gewählten Zeitraum
$sql = "
  SELECT u.id, u.vorname, u.nachname,
    ROUND(SUM(TIMESTAMPDIFF(SECOND, z.startzeit, z.endzeit))/3600, 2) AS stunden
  FROM users u
  LEFT JOIN zeiterfassung z
    ON z.kamerad_id = u.id
    AND z.endzeit IS NOT NULL
    AND z.startzeit BETWEEN ? AND ?
  WHERE u.einheit = ?
  GROUP BY u.id
  ORDER BY stunden DESC
";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $startdatum, $enddatum, $einheit);
$stmt->execute();
$ergebnis = $stmt->get_result();

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

while ($row = $ergebnis->fetch_assoc()) {
    $name = $row['vorname'] . ' ' . $row['nachname'];
    $labels[] = $name;
    $werte[] = $row['stunden'] ?? 0;
}
?>

<div class="container my-5">
  <h2 class="mb-4">⏱️ Zeiten aller Kameraden – <?= date("F Y", strtotime($startdatum)) ?></h2>

  <form method="get" class="row g-3 mb-4">
    <div class="col-auto">
      <label for="monat" class="form-label">Monat</label>
      <select name="monat" id="monat" class="form-select">
        <?php for ($m = 1; $m <= 12; $m++): ?>
          <option value="<?= str_pad($m, 2, '0', STR_PAD_LEFT) ?>" <?= $monat == str_pad($m, 2, '0', STR_PAD_LEFT) ? 'selected' : '' ?>>
            <?= strftime('%B', mktime(0, 0, 0, $m, 1)) ?>
          </option>
        <?php endfor; ?>
      </select>
    </div>
    <div class="col-auto">
      <label for="jahr" class="form-label">Jahr</label>
      <select name="jahr" id="jahr" class="form-select">
        <?php for ($y = date('Y'); $y >= 2022; $y--): ?>
          <option value="<?= $y ?>" <?= $jahr == $y ? 'selected' : '' ?>><?= $y ?></option>
        <?php endfor; ?>
      </select>
    </div>
    <div class="col-auto align-self-end">
      <button class="btn btn-primary">Filtern</button>
    </div>
  </form>

  <canvas id="alleKameradenChart" height="100"></canvas>
</div>

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

<?php include 'includes/footer.php'; ?>
