<?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'] ?? '';
$kamerad_id = (int)($_GET['id'] ?? 0);
$monat = $_GET['monat'] ?? date('m');
$jahr = $_GET['jahr'] ?? date('Y');
$startdatum = "$jahr-$monat-01";
$enddatum = date("Y-m-t", strtotime($startdatum));

// Kameradendaten laden
$stmt = $conn->prepare("SELECT vorname, nachname FROM users WHERE id = ? AND einheit = ?");
$stmt->bind_param("is", $kamerad_id, $einheit);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    echo "<div class='container my-5'><div class='alert alert-danger'>Kamerad nicht gefunden oder Zugriff verweigert.</div></div>";
    include 'includes/footer.php';
    exit;
}

// Zeiteinträge laden
$sql = "SELECT startzeit, endzeit, TIMESTAMPDIFF(SECOND, startzeit, endzeit) AS sekunden
        FROM zeiterfassung
        WHERE kamerad_id = ? AND startzeit BETWEEN ? AND ? AND endzeit IS NOT NULL
        ORDER BY startzeit DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iss", $kamerad_id, $startdatum, $enddatum);
$stmt->execute();
$eintraege = $stmt->get_result();
?>

<div class="container my-5">
  <h2 class="mb-4">📅 Zeiteinträge – <?= htmlspecialchars($user['vorname'] . ' ' . $user['nachname']) ?> (<?= strftime('%B %Y', strtotime($startdatum)) ?>)</h2>

  <a href="zeiterfassung_statistik.php?monat=<?= $monat ?>&jahr=<?= $jahr ?>" class="btn btn-secondary mb-4">⬅️ Zurück zur Übersicht</a>

  <div class="table-responsive">
    <table class="table table-striped table-bordered">
      <thead class="table-dark">
        <tr>
          <th>#</th>
          <th>Startzeit</th>
          <th>Endzeit</th>
          <th>Dauer (Stunden)</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $index = 1;
        $summe = 0;
        while ($row = $eintraege->fetch_assoc()):
            $dauer = round($row['sekunden'] / 3600, 2);
            $summe += $dauer;
        ?>
        <tr>
          <td><?= $index++ ?></td>
          <td><?= date('d.m.Y H:i', strtotime($row['startzeit'])) ?></td>
          <td><?= date('d.m.Y H:i', strtotime($row['endzeit'])) ?></td>
          <td><?= number_format($dauer, 2, ',', '.') ?></td>
        </tr>
        <?php endwhile; ?>
      </tbody>
      <tfoot class="table-light">
        <tr>
          <th colspan="3" class="text-end">Gesamt</th>
          <th><?= number_format($summe, 2, ',', '.') ?> h</th>
        </tr>
      </tfoot>
    </table>
    <?php
// Tagesverteilung vorbereiten
$tagesstunden = array_fill(1, date("t", strtotime($startdatum)), 0);

$stmt = $conn->prepare("SELECT startzeit, endzeit FROM zeiterfassung WHERE kamerad_id = ? AND startzeit BETWEEN ? AND ? AND endzeit IS NOT NULL");
$stmt->bind_param("iss", $kamerad_id, $startdatum, $enddatum);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    $tag = (int)date('j', strtotime($row['startzeit']));
    $dauer = round((strtotime($row['endzeit']) - strtotime($row['startzeit'])) / 3600, 2);
    $tagesstunden[$tag] += $dauer;
}
?>

<div class="mt-5">
  <h4>📈 Tagesverteilung im Monat</h4>
  <canvas id="tageChart" height="100"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctxTage = document.getElementById('tageChart').getContext('2d');
new Chart(ctxTage, {
  type: 'bar',
  data: {
    labels: <?= json_encode(array_keys($tagesstunden)) ?>,
    datasets: [{
      label: 'Arbeitsstunden',
      data: <?= json_encode(array_values($tagesstunden)) ?>,
      backgroundColor: 'rgba(255, 193, 7, 0.6)',
      borderColor: 'rgba(255, 193, 7, 1)',
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      y: {
        beginAtZero: true,
        title: { display: true, text: 'Stunden' }
      },
      x: {
        title: { display: true, text: 'Tag im Monat' }
      }
    }
  }
});
</script>

  </div>
</div>

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