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

$rfid = $_GET['rfid'] ?? '';
$meldung = '';
$eintraege = [];

if ($rfid) {
    // Benutzer abrufen
    $stmt = $conn->prepare("SELECT id, vorname, nachname FROM users WHERE rfid_card = ?");
    $stmt->bind_param("s", $rfid);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    if ($user) {
        $user_id = (int)$user['id'];
        $vorname = $user['vorname'];
        $nachname = $user['nachname'];

        // Zeiteinträge laden
        $stmt = $conn->prepare("
            SELECT z.*, k.bezeichnung AS kostenstelle
            FROM zeiterfassung z
            LEFT JOIN kostenstellen k ON k.id = z.kostenstelle_id
            WHERE z.kamerad_id = ?
            ORDER BY z.startzeit DESC
            LIMIT 50
        ");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $eintraege = $stmt->get_result();
    } else {
        $meldung = '<div class="alert alert-danger">RFID-Karte nicht gefunden.</div>';
    }
} else {
    $meldung = '<div class="alert alert-warning">Keine RFID übergeben.</div>';
}
?>

<div class="container my-5">
  <h2 class="mb-4">📋 Zeiteinträge <?= isset($vorname) ? 'von ' . htmlspecialchars($vorname . ' ' . $nachname) : '' ?></h2>
  <?= $meldung ?>

  <?php if ($eintraege && $eintraege->num_rows > 0): ?>
  <div class="table-responsive">
    <table class="table table-bordered table-striped">
      <thead class="table-dark">
        <tr>
          <th>Start</th>
          <th>Ende</th>
          <th>Dauer (h)</th>
          <th>Kostenstelle</th>
          <th>Erfasst</th>
        </tr>
      </thead>
      <tbody>
        <?php while ($z = $eintraege->fetch_assoc()):
          $start = strtotime($z['startzeit']);
          $ende = strtotime($z['endzeit']);
          $dauer = ($ende && $z['endzeit']) ? round(($ende - $start) / 3600, 2) : '-';
        ?>
        <tr>
          <td><?= date("d.m.Y H:i", $start) ?></td>
          <td><?= $z['endzeit'] ? date("d.m.Y H:i", $ende) : '<span class="text-danger fw-bold">läuft</span>' ?></td>
          <td><?= is_numeric($dauer) ? number_format($dauer, 2, ',', '.') : '–' ?></td>
          <td><?= htmlspecialchars($z['kostenstelle'] ?? '-') ?></td>
          <td><?= $z['manuell'] ? '📝 manuell' : '⏱️ automatisch' ?></td>
        </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div>
  <?php elseif (!$meldung): ?>
    <div class="alert alert-info">Keine Zeiteinträge gefunden.</div>
  <?php endif; ?>

  <a href="terminal.php" class="btn btn-secondary mt-4">⬅️ Zurück zum Terminal</a>
</div>

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