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

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

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

// Kategorien
$kategorien_dropdown = ['Bilder', 'Prüfunterlagen', 'Bedienungsanleitungen', 'Messwerte'];

// Datei hochladen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload'])) {
    $kategorie = trim($_POST['kategorie']);
    $barcode = trim($_POST['barcode']);
    $anzeigename = trim($_POST['anzeigename']);

    if (!empty($_FILES['datei']['name']) && in_array($kategorie, $kategorien_dropdown)) {
        $uploadDir = 'uploads/dokumente/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

        $ext = pathinfo($_FILES['datei']['name'], PATHINFO_EXTENSION);
        $filename = uniqid('dokument_') . '.' . $ext;
        $fullPath = $uploadDir . $filename;

        if (move_uploaded_file($_FILES['datei']['tmp_name'], $fullPath)) {
            $stmt = $conn->prepare("INSERT INTO dokumente (dateiname, anzeigename, kategorie, barcode, einheit) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("sssss", $filename, $anzeigename, $kategorie, $barcode, $einheit);
            $stmt->execute();
            $meldung = "<div class='alert alert-success'>Datei erfolgreich hochgeladen.</div>";
        } else {
            $meldung = "<div class='alert alert-danger'>Upload fehlgeschlagen.</div>";
        }
    }
}

// Datei löschen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $id = (int)$_POST['delete_id'];
    $stmt = $conn->prepare("SELECT dateiname FROM dokumente WHERE id = ? AND einheit = ?");
    $stmt->bind_param("is", $id, $einheit);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();

    if ($res) {
        unlink("uploads/dokumente/" . $res['dateiname']);
        $stmt = $conn->prepare("DELETE FROM dokumente WHERE id = ? AND einheit = ?");
        $stmt->bind_param("is", $id, $einheit);
        $stmt->execute();
        $meldung = "<div class='alert alert-success'>Datei gelöscht.</div>";
    }
}

// Dokument bearbeiten
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_id'])) {
    $id = (int)$_POST['edit_id'];
    $anzeigename = trim($_POST['edit_anzeigename']);
    $kategorie = trim($_POST['edit_kategorie']);
    if (in_array($kategorie, $kategorien_dropdown)) {
        $stmt = $conn->prepare("UPDATE dokumente SET anzeigename = ?, kategorie = ? WHERE id = ? AND einheit = ?");
        $stmt->bind_param("ssis", $anzeigename, $kategorie, $id, $einheit);
        $stmt->execute();
        $meldung = "<div class='alert alert-success'>Eintrag aktualisiert.</div>";
    }
}

// Dokumente laden
$filter = $_GET['filter'] ?? '';
if ($filter) {
    $stmt = $conn->prepare("SELECT * FROM dokumente WHERE kategorie = ? AND einheit = ? ORDER BY hochgeladen_am DESC");
    $stmt->bind_param("ss", $filter, $einheit);
} else {
    $stmt = $conn->prepare("SELECT * FROM dokumente WHERE einheit = ? ORDER BY hochgeladen_am DESC");
    $stmt->bind_param("s", $einheit);
}
$stmt->execute();
$dokumente = $stmt->get_result();

$kats = $conn->prepare("SELECT DISTINCT kategorie FROM dokumente WHERE einheit = ? ORDER BY kategorie");
$kats->bind_param("s", $einheit);
$kats->execute();
$kat_result = $kats->get_result();
?>

<div class="container my-5">
  <h2 class="mb-4">Dokumentenverwaltung – Einheit: <?= htmlspecialchars($einheit) ?></h2>
  <?= $meldung ?>

  <form method="post" enctype="multipart/form-data" class="card p-4 mb-4 bg-light">
    <h5>Datei hochladen</h5>
    <div class="row">
      <div class="col-md-3"><input type="file" name="datei" class="form-control mb-2" required></div>
      <div class="col-md-3"><input type="text" name="anzeigename" class="form-control mb-2" placeholder="Anzeigename" required></div>
      <div class="col-md-2">
        <select name="kategorie" class="form-select mb-2" required>
          <option value="">-- Kategorie --</option>
          <?php foreach ($kategorien_dropdown as $kat): ?>
            <option value="<?= $kat ?>"><?= $kat ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2"><input type="text" name="barcode" class="form-control mb-2" placeholder="Geräte-Barcode (optional)"></div>
      <div class="col-md-2"><button type="submit" name="upload" class="btn btn-primary w-100">Hochladen</button></div>
    </div>
  </form>

  <form method="get" class="mb-3">
    <label>Kategorie filtern:</label>
    <select name="filter" class="form-select w-auto d-inline-block" onchange="this.form.submit()">
      <option value="">Alle</option>
      <?php while ($k = $kat_result->fetch_assoc()): ?>
        <option value="<?= $k['kategorie'] ?>" <?= $filter == $k['kategorie'] ? 'selected' : '' ?>>
          <?= htmlspecialchars($k['kategorie']) ?>
        </option>
      <?php endwhile; ?>
    </select>
  </form>

  <div class="table-responsive">
    <table class="table table-bordered bg-white">
      <thead class="table-dark">
        <tr>
          <th>Anzeigename</th>
          <th>Kategorie</th>
          <th>Geräte-Barcode</th>
          <th>Hochgeladen</th>
          <th>Aktionen</th>
        </tr>
      </thead>
      <tbody>
        <?php while ($d = $dokumente->fetch_assoc()): ?>
          <tr>
            <td><?= htmlspecialchars($d['anzeigename']) ?></td>
            <td><?= htmlspecialchars($d['kategorie']) ?></td>
            <td><?= htmlspecialchars($d['barcode'] ?: '-') ?></td>
            <td><?= date("d.m.Y H:i", strtotime($d['hochgeladen_am'])) ?></td>
            <td>
              <a href="uploads/dokumente/<?= $d['dateiname'] ?>" target="_blank" class="btn btn-sm btn-outline-primary">Ansehen</a>
              <form method="post" class="d-inline-block">
                <input type="hidden" name="delete_id" value="<?= $d['id'] ?>">
                <button class="btn btn-sm btn-outline-danger" onclick="return confirm('Wirklich löschen?')">Löschen</button>
              </form>
              <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#edit<?= $d['id'] ?>">Bearbeiten</button>
              <div id="edit<?= $d['id'] ?>" class="collapse mt-2">
                <form method="post" class="d-flex flex-wrap gap-2 mt-2">
                  <input type="hidden" name="edit_id" value="<?= $d['id'] ?>">
                  <input type="text" name="edit_anzeigename" value="<?= htmlspecialchars($d['anzeigename']) ?>" class="form-control w-auto" required>
                  <select name="edit_kategorie" class="form-select w-auto">
                    <?php foreach ($kategorien_dropdown as $kat): ?>
                      <option value="<?= $kat ?>" <?= $kat == $d['kategorie'] ? 'selected' : '' ?>><?= $kat ?></option>
                    <?php endforeach; ?>
                  </select>
                  <button class="btn btn-sm btn-success">Speichern</button>
                </form>
              </div>
            </td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</div>

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