<?php
// dokumente.php – Dokumentenverwaltung (UI & Menüs wie geraete.php)
ob_start();
session_start();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/nav.php';
require_once __DIR__ . '/includes/db.php';

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

$einheit = $_SESSION['einheit'] ?? '';
if ($einheit === '') {
  echo "<div class='container my-5'><div class='alert alert-warning'>⚠️ Keine Einheit in der Session gefunden. Bitte erneut einloggen.</div></div>";
  include 'includes/footer.php'; exit;
}

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function fmtDate($v){
  if (!$v) return '—';
  $ts = is_numeric($v) ? (int)$v : strtotime($v);
  return $ts ? date('d.m.Y H:i', $ts) : '—';
}

// CSRF
if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(16)); }
$CSRF = $_SESSION['csrf'];

$meldung = '';
$kategorien_dropdown = ['Bilder','Prüfunterlagen','Bedienungsanleitungen','Messwerte','Dienstanweisungen'];

/* ---------------- Aktionen: Upload / Edit / Delete ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // CSRF für mutierende Aktionen
  if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $meldung = "<div class='alert alert-danger'>Sicherheitsprüfung fehlgeschlagen.</div>";
  } else {
    // Upload
    if (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, true)) {
        $uploadDir = __DIR__ . '/uploads/dokumente/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

        $orig = $_FILES['datei']['name'];
        $ext  = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
        $filename = uniqid('dokument_', true) . ($ext ? '.'.$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>";
        }
      } else {
        $meldung = "<div class='alert alert-warning'>Bitte Datei und gültige Kategorie wählen.</div>";
      }
    }

    // Bearbeiten (Anzeigename/Kategorie/Barcode ändern)
    if (isset($_POST['edit_id'])) {
      $id          = (int)$_POST['edit_id'];
      $anzeigename = trim($_POST['edit_anzeigename'] ?? '');
      $kategorie   = trim($_POST['edit_kategorie'] ?? '');
      $barcode     = trim($_POST['edit_barcode'] ?? '');
      if ($id > 0 && $anzeigename !== '' && in_array($kategorie, $kategorien_dropdown, true)) {
        $st = $conn->prepare("UPDATE dokumente SET anzeigename=?, kategorie=?, barcode=? WHERE id=? AND einheit=?");
        $st->bind_param("sssds", $anzeigename, $kategorie, $barcode, $id, $einheit);
        // Achtung: 'd' bindet double; besser i für id:
        $st->close(); // Korrigieren:
        $st = $conn->prepare("UPDATE dokumente SET anzeigename=?, kategorie=?, barcode=? WHERE id=? AND einheit=?");
        $st->bind_param("sssds", $anzeigename, $kategorie, $barcode, $id, $einheit);
      }
    }

    // Korrigierte Bind-Types (oben war ein Tippfehler):
    if (isset($_POST['edit_id'])) {
      $id          = (int)$_POST['edit_id'];
      $anzeigename = trim($_POST['edit_anzeigename'] ?? '');
      $kategorie   = trim($_POST['edit_kategorie'] ?? '');
      $barcode     = trim($_POST['edit_barcode'] ?? '');
      if ($id > 0 && $anzeigename !== '' && in_array($kategorie, $kategorien_dropdown, true)) {
        $st = $conn->prepare("UPDATE dokumente SET anzeigename=?, kategorie=?, barcode=? WHERE id=? AND einheit=?");
        $st->bind_param("sssis", $anzeigename, $kategorie, $barcode, $id, $einheit);
        $meldung = $st->execute()
          ? "<div class='alert alert-success'>✅ Eintrag aktualisiert.</div>"
          : "<div class='alert alert-danger'>❌ Aktualisierung fehlgeschlagen.</div>";
      } else {
        $meldung = "<div class='alert alert-warning'>Bitte gültige Werte angeben.</div>";
      }
    }

    // Löschen
    if (isset($_POST['delete_id'])) {
      $id = (int)$_POST['delete_id'];
      $st = $conn->prepare("SELECT dateiname FROM dokumente WHERE id=? AND einheit=?");
      $st->bind_param("is", $id, $einheit);
      $st->execute();
      $res = $st->get_result()->fetch_assoc();
      if ($res) {
        $filePath = __DIR__ . "/uploads/dokumente/" . $res['dateiname'];
        if (is_file($filePath)) { @unlink($filePath); }
        $del = $conn->prepare("DELETE FROM dokumente WHERE id=? AND einheit=?");
        $del->bind_param("is", $id, $einheit);
        $del->execute();
        $meldung = "<div class='alert alert-success'>🗑️ Datei gelöscht.</div>";
      } else {
        $meldung = "<div class='alert alert-info'>Kein Eintrag gefunden.</div>";
      }
    }
  }
}

/* ---------------- Filter / Suche ---------------- */
$search = trim($_GET['search'] ?? '');
$filter = trim($_GET['filter'] ?? '');

$where  = "einheit = ?";
$types  = "s";
$params = [$einheit];

if ($filter !== '') {
  $where .= " AND kategorie = ?";
  $params[] = $filter; $types .= "s";
}
if ($search !== '') {
  $like = '%'.$search.'%';
  $where .= " AND (anzeigename LIKE ? OR barcode LIKE ? OR kategorie LIKE ?)";
  $params[] = $like; $types .= "s";
  $params[] = $like; $types .= "s";
  $params[] = $like; $types .= "s";
}

/* ---------------- CSV Export ---------------- */
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
  $fn = 'dokumente_export_' . date('Y-m-d') . '.csv';
  header('Content-Type: text/csv; charset=utf-8');
  header("Content-Disposition: attachment; filename=\"$fn\"");
  $out = fopen('php://output','w');
  fputcsv($out, ['Anzeigename','Kategorie','Barcode','Dateiname','Hochgeladen','Einheit']);
  $sqlE = "SELECT anzeigename,kategorie,barcode,dateiname,hochgeladen_am,einheit FROM dokumente WHERE $where ORDER BY hochgeladen_am DESC";
  $stE = $conn->prepare($sqlE);
  $a = [$types]; foreach($params as $k=>$_){ $a[] = &$params[$k]; }
  call_user_func_array([$stE,'bind_param'],$a);
  $stE->execute();
  $resE = $stE->get_result();
  while($r=$resE->fetch_assoc()){
    fputcsv($out, [$r['anzeigename'],$r['kategorie'],$r['barcode'],$r['dateiname'],fmtDate($r['hochgeladen_am']),$r['einheit']]);
  }
  fclose($out); exit;
}

/* ---------------- Daten laden ---------------- */
$sql = "SELECT * FROM dokumente WHERE $where ORDER BY hochgeladen_am DESC";
$st = $conn->prepare($sql);
$a = [$types]; foreach($params as $k=>$_){ $a[] = &$params[$k]; }
call_user_func_array([$st,'bind_param'],$a);
$st->execute();
$dokumente = $st->get_result();

// Kategorienliste aus DB (für Filter)
$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();
?>
<style>
  .toolbar .btn, .toolbar .form-control, .toolbar .form-select{ height:38px }
  .text-mono{font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;}
</style>

<div class="container my-5">
  <!-- Toolbar wie geraete.php -->
  <div class="d-flex flex-wrap justify-content-between align-items-end gap-2 mb-3">
    <div>
      <h2 class="mb-1">Dokumentenverwaltung</h2>
      <div class="text-muted small">Einheit: <span class="badge text-bg-secondary"><?= h($einheit) ?></span></div>
    </div>
    <div class="toolbar d-flex flex-wrap gap-2">
      <form method="get" class="d-flex flex-wrap gap-2">
        <input type="text" name="search" class="form-control" placeholder="🔍 Suche: Anzeigename / Barcode / Kategorie" value="<?= h($search) ?>">
        <select name="filter" class="form-select">
          <option value="">Alle Kategorien</option>
          <?php while ($k = $kat_result->fetch_assoc()): ?>
            <option value="<?= h($k['kategorie']) ?>" <?= $filter===$k['kategorie']?'selected':'' ?>><?= h($k['kategorie']) ?></option>
          <?php endwhile; ?>
        </select>
        <button class="btn btn-outline-primary">Anwenden</button>
        <?php if ($search!=='' || $filter!==''): ?>
          <a href="dokumente.php" class="btn btn-outline-secondary">Zurücksetzen</a>
        <?php endif; ?>
        <a href="?export=csv&<?= http_build_query(['search'=>$search,'filter'=>$filter]) ?>" class="btn btn-outline-secondary">CSV Export</a>
      </form>
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#uploadModal">➕ Upload</button>
    </div>
  </div>

  <?= $meldung ?>

  <div class="card shadow-sm">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>Anzeigename</th>
            <th>Kategorie</th>
            <th>Geräte-Barcode</th>
            <th>Hochgeladen</th>
            <th class="text-end" style="width:60px;"></th>
          </tr>
        </thead>
        <tbody>
          <?php if ($dokumente->num_rows === 0): ?>
            <tr><td colspan="5" class="text-center text-muted py-4">Keine Dokumente gefunden.</td></tr>
          <?php else: while ($d = $dokumente->fetch_assoc()): ?>
            <?php
              $id = (int)$d['id'];
              $fileHref = 'uploads/dokumente/' . $d['dateiname'];
            ?>
            <tr>
              <td class="fw-semibold"><?= h($d['anzeigename']) ?></td>
              <td><?= h($d['kategorie']) ?></td>
              <td class="text-mono"><?= h($d['barcode'] ?: '—') ?></td>
              <td><?= fmtDate($d['hochgeladen_am']) ?></td>
              <td class="text-end">
                <div class="dropdown">
                  <button class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">Aktionen</button>
                  <div class="dropdown-menu dropdown-menu-end">
                    <a class="dropdown-item" href="<?= h($fileHref) ?>" target="_blank">Ansehen</a>
                    <button class="dropdown-item" data-bs-toggle="modal" data-bs-target="#editModal<?= $id ?>">Bearbeiten</button>
                    <div class="dropdown-divider"></div>
                    <form method="post" class="px-3 py-1" onsubmit="return confirm('Wirklich löschen?');">
                      <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                      <input type="hidden" name="delete_id" value="<?= $id ?>">
                      <button class="dropdown-item text-danger">Löschen</button>
                    </form>
                  </div>
                </div>
              </td>
            </tr>

            <!-- Edit Modal -->
            <div class="modal fade" id="editModal<?= $id ?>" tabindex="-1" aria-hidden="true">
              <div class="modal-dialog">
                <form method="post" class="modal-content">
                  <div class="modal-header">
                    <h5 class="modal-title">Dokument bearbeiten</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                  </div>
                  <div class="modal-body">
                    <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                    <input type="hidden" name="edit_id" value="<?= $id ?>">
                    <div class="mb-3">
                      <label class="form-label">Anzeigename</label>
                      <input type="text" name="edit_anzeigename" class="form-control" value="<?= h($d['anzeigename']) ?>" required>
                    </div>
                    <div class="mb-3">
                      <label class="form-label">Kategorie</label>
                      <select name="edit_kategorie" class="form-select" required>
                        <?php foreach ($kategorien_dropdown as $kat): ?>
                          <option value="<?= h($kat) ?>" <?= ($kat === $d['kategorie'])?'selected':'' ?>><?= h($kat) ?></option>
                        <?php endforeach; ?>
                      </select>
                    </div>
                    <div class="mb-0">
                      <label class="form-label">Geräte-Barcode (optional)</label>
                      <input type="text" name="edit_barcode" class="form-control" value="<?= h($d['barcode']) ?>">
                    </div>
                  </div>
                  <div class="modal-footer">
                    <button class="btn btn-primary">Speichern</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
                  </div>
                </form>
              </div>
            </div>
          <?php endwhile; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Upload Modal -->
<div class="modal fade" id="uploadModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" enctype="multipart/form-data" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Datei hochladen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
        <div class="mb-3">
          <label class="form-label">Datei</label>
          <input type="file" name="datei" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Anzeigename</label>
          <input type="text" name="anzeigename" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Kategorie</label>
          <select name="kategorie" class="form-select" required>
            <option value="">– Kategorie wählen –</option>
            <?php foreach ($kategorien_dropdown as $kat): ?>
              <option value="<?= h($kat) ?>"><?= h($kat) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="mb-0">
          <label class="form-label">Geräte-Barcode (optional)</label>
          <input type="text" name="barcode" class="form-control" placeholder="z. B. G1234">
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" name="upload">Hochladen</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
      </div>
    </form>
  </div>
</div>

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