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

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

$user_id = (int)$_SESSION['user_id'];
$vorname = $_SESSION['user_vorname'] ?? '';
$nachname = $_SESSION['user_nachname'] ?? '';
$meldung = '';

// Kostenstellen laden
$ks_result = $conn->query("SELECT id, bezeichnung FROM kostenstellen ORDER BY bezeichnung");

// Letzter offener Eintrag
$stmt = $conn->prepare("SELECT * FROM zeiterfassung WHERE kamerad_id = ? AND endzeit IS NULL ORDER BY startzeit DESC LIMIT 1");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$offen = $stmt->get_result()->fetch_assoc();

// Start
if (isset($_POST['start']) && isset($_POST['kostenstelle_id']) && !$offen) {
    $ks = (int)$_POST['kostenstelle_id'];
    $stmt = $conn->prepare("INSERT INTO zeiterfassung (kamerad_id, startzeit, kostenstelle_id) VALUES (?, NOW(), ?)");
    $stmt->bind_param("ii", $user_id, $ks);
    $stmt->execute();
    header("Location: zeiterfassung.php");
    exit;
}

// Ende
if (isset($_POST['ende']) && $offen) {
    $stmt = $conn->prepare("UPDATE zeiterfassung SET endzeit = NOW() WHERE id = ?");
    $stmt->bind_param("i", $offen['id']);
    $stmt->execute();
    header("Location: zeiterfassung.php");
    exit;
}

// Manuell
if (isset($_POST['manuell'])) {
    $start = $_POST['startzeit'];
    $ende = $_POST['endzeit'];
    $ks = (int)$_POST['kostenstelle_id'];
    if ($start && $ende) {
        $stmt = $conn->prepare("INSERT INTO zeiterfassung (kamerad_id, startzeit, endzeit, kostenstelle_id, manuell) VALUES (?, ?, ?, ?, 1)");
        $stmt->bind_param("issi", $user_id, $start, $ende, $ks);
        $stmt->execute();
        $meldung = '<div class="alert alert-success">Manueller Eintrag gespeichert.</div>';
    }
}
?>

<div class="container my-5">
  <h2 class="mb-4">⏱️ Zeiterfassung für <?= htmlspecialchars($vorname . ' ' . $nachname) ?></h2>
  <?= $meldung ?>

  <form method="post">
    <?php if ($offen): ?>
      <div class="alert alert-warning">Erfassung läuft seit <strong><?= date("d.m.Y H:i", strtotime($offen['startzeit'])) ?></strong>.</div>
      <button name="ende" class="btn btn-danger btn-lg">⏹️ Erfassen beenden</button>
    <?php else: ?>
      <div class="row g-2 align-items-end mb-3">
        <div class="col-md-6">
          <label class="form-label">Kostenstelle</label>
          <select name="kostenstelle_id" class="form-select" required>
            <option value="">-- bitte wählen --</option>
            <?php foreach ($ks_result as $ks): ?>
              <option value="<?= $ks['id'] ?>"><?= htmlspecialchars($ks['bezeichnung']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <button name="start" class="btn btn-success btn-lg w-100">▶️ Erfassen starten</button>
        </div>
      </div>
    <?php endif; ?>
  </form>

  <hr class="my-4">

  <h4>🔧 Manueller Zeiteintrag</h4>
  <form method="post" class="row g-3">
    <input type="hidden" name="manuell" value="1">
    <div class="col-md-6">
      <label class="form-label">Startzeit</label>
      <input type="datetime-local" name="startzeit" class="form-control" required>
    </div>
    <div class="col-md-6">
      <label class="form-label">Endzeit</label>
      <input type="datetime-local" name="endzeit" class="form-control" required>
    </div>
    <div class="col-md-12">
      <label class="form-label">Kostenstelle</label>
      <select name="kostenstelle_id" class="form-select" required>
        <option value="">-- bitte wählen --</option>
        <?php
        $ks_result2 = $conn->query("SELECT id, bezeichnung FROM kostenstellen ORDER BY bezeichnung");
        foreach ($ks_result2 as $ks): ?>
          <option value="<?= $ks['id'] ?>"><?= htmlspecialchars($ks['bezeichnung']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-12">
      <button class="btn btn-secondary">💾 Speichern</button>
    </div>
  </form>


<hr class="my-5">
<h4>📋 Deine bisherigen Zeiteinträge</h4>

<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
      $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 100
      ");
      $stmt->bind_param("i", $user_id);
      $stmt->execute();
      $zeiten = $stmt->get_result();

      while ($z = $zeiten->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>
</div>
<?php include 'dashboard_zeiterfassung.php'; ?>
<?php include 'includes/footer.php'; ?>
<?php ob_end_flush(); ?>
