<?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>';
    }
}
?>

<style>
  .zf-hero {
    background: linear-gradient(135deg, #f8f9ff 0%, #eef5ff 100%);
    border: 1px solid #e9eef7;
    border-radius: 18px;
  }
  .zf-kpi {
    border-radius: 14px;
  }
  .zf-running {
    animation: pulseShadow 1.6s ease-in-out infinite;
  }
  @keyframes pulseShadow {
    0%   { box-shadow: 0 0 0 0 rgba(25,135,84,.25); }
    70%  { box-shadow: 0 0 0 12px rgba(25,135,84,0); }
    100% { box-shadow: 0 0 0 0 rgba(25,135,84,0); }
  }
  .table thead th { white-space: nowrap; }
  .pill {
    display:inline-block; padding:.25rem .6rem; border-radius: 999px; font-size:.85rem;
    background:#f1f3f5; border:1px solid #e9ecef;
  }
</style>

<div class="container my-5">

  <!-- HERO / Kopfbereich -->
  <div class="zf-hero p-4 p-md-5 mb-4">
    <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
      <div>
        <h2 class="mb-1">⏱️ Zeiterfassung</h2>
        <div class="text-muted">für <?= htmlspecialchars($vorname . ' ' . $nachname) ?></div>
      </div>
      <div class="d-flex gap-2">
        <a href="dashboard_zeiterfassung.php" class="btn btn-outline-primary">
          <i class="bi bi-graph-up-arrow me-1"></i> Auswertung
        </a>
      </div>
    </div>
  </div>

  <?= $meldung ?>

  <!-- Laufende Erfassung / Start-Stop -->
  <div class="row g-4">
    <div class="col-12 col-lg-6">
      <form method="post">
        <?php if ($offen): ?>
          <div class="card border-success zf-running">
            <div class="card-body">
              <div class="d-flex align-items-center justify-content-between">
                <div>
                  <div class="text-success fw-semibold mb-1">
                    <i class="bi bi-record-circle me-1"></i> Erfassung läuft
                  </div>
                  <div class="small text-muted">
                    Seit <strong><?= date("d.m.Y H:i", strtotime($offen['startzeit'])) ?></strong>
                  </div>
                </div>
                <button name="ende" class="btn btn-danger btn-lg">
                  ⏹️ Beenden
                </button>
              </div>
            </div>
          </div>
        <?php else: ?>
          <div class="card shadow-sm">
            <div class="card-body">
              <div class="mb-3">
                <label class="form-label">Kostenstelle</label>
                <select name="kostenstelle_id" class="form-select form-select-lg" 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="d-grid">
                <button name="start" class="btn btn-success btn-lg">
                  ▶️ Erfassen starten
                </button>
              </div>
            </div>
          </div>
        <?php endif; ?>
      </form>
    </div>

    <!-- Manuelle Erfassung -->
    <div class="col-12 col-lg-6">
      <div class="card shadow-sm h-100">
        <div class="card-body">
          <div class="d-flex align-items-center justify-content-between mb-3">
            <h4 class="mb-0">🔧 Manueller Zeiteintrag</h4>
            <span class="pill">Korrekturen / Nachtrag</span>
          </div>
          <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 d-grid">
              <button class="btn btn-secondary">
                💾 Speichern
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

  <!-- Liste -->
  <div class="d-flex align-items-center justify-content-between mt-5 mb-2">
    <h4 class="mb-0">📋 Deine bisherigen Zeiteinträge</h4>
    <div class="text-muted small">Letzte 100 Einträge</div>
  </div>

  <div class="table-responsive">
    <table class="table table-bordered table-striped align-middle">
      <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) : '-';
          $running = empty($z['endzeit']);
          ?>
          <tr class="<?= $running ? 'table-warning' : '' ?>">
            <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>
              <?php if (is_numeric($dauer)): ?>
                <span class="pill"><?= number_format($dauer, 2, ',', '.') ?></span>
              <?php else: ?>
                –
              <?php endif; ?>
            </td>
            <td><?= htmlspecialchars($z['kostenstelle'] ?? '-') ?></td>
            <td>
              <?php if ($z['manuell']): ?>
                <span class="badge text-bg-secondary">📝 manuell</span>
              <?php else: ?>
                <span class="badge text-bg-success">⏱️ automatisch</span>
              <?php endif; ?>
            </td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div>

</div>

<?php include 'dashboard_zeiterfassung.php'; ?>
<?php include 'includes/footer.php'; ?>
<?php ob_end_flush(); ?>
