<?php
// dokumente.php – Dokumentenverwaltung (Windows Explorer Style)
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', $ts) : '';
}

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

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

/* ---------------- PHP Logik (Upload/Edit/Delete) UNVERÄNDERT ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  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 btn-sm mb-3'>✅ Datei erfolgreich hochgeladen.</div>";
        } else {
          $meldung = "<div class='alert alert-danger btn-sm mb-3'>❌ Upload fehlgeschlagen.</div>";
        }
      } else {
        $meldung = "<div class='alert alert-warning btn-sm mb-3'>Bitte Datei und gültige Kategorie wählen.</div>";
      }
    }

    // Bearbeiten
    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 btn-sm mb-3'>✅ Eintrag aktualisiert.</div>"
          : "<div class='alert alert-danger btn-sm mb-3'>❌ Aktualisierung fehlgeschlagen.</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 btn-sm mb-3'>🗑️ Datei gelöscht.</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();

$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();
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">

<style>
  /* Windows Explorer Style CSS */
  .explorer-container {
    display: flex;
    flex-wrap: wrap;
    gap: 5px; /* Enger Abstand zwischen Items */
    align-items: flex-start;
  }

  /* Das einzelne Datei-Objekt */
  .win-item {
    width: 110px;        /* Fixe Breite, schmal */
    padding: 10px 5px;
    border: 1px solid transparent;
    border-radius: 3px;
    text-align: center;
    cursor: default;
    position: relative;
    transition: background-color 0.1s, border-color 0.1s;
  }

  /* Windows Hover Effekt (Hellblau) */
  .win-item:hover {
    background-color: #e5f3ff;
    border-color: #cce8ff;
  }

  /* Das Icon */
  .win-icon {
    font-size: 2.8rem; /* Nicht zu riesig */
    line-height: 1;
    margin-bottom: 6px;
    display: block;
    filter: drop-shadow(0 2px 3px rgba(0,0,0,0.1));
  }

  /* Der Dateiname */
  .win-label {
    font-size: 0.8rem;
    color: #212529;
    line-height: 1.2;
    word-wrap: break-word;
    /* Max 2 Zeilen Text, dann ... */
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  /* Das Kontext-Menü (3 Punkte) - erscheint nur beim Hovern oben rechts */
  .win-menu-btn {
    position: absolute;
    top: 2px;
    right: 2px;
    padding: 0;
    width: 20px;
    height: 20px;
    font-size: 14px;
    border: none;
    background: transparent;
    color: #666;
    display: none; /* Standardmäßig versteckt */
    border-radius: 3px;
  }
  .win-item:hover .win-menu-btn {
    display: block; /* Zeigen bei Hover */
    background-color: #cce8ff;
  }
  .win-menu-btn:hover {
    background-color: #99d1ff !important;
  }

  /* Kategorie Badge in klein */
  .win-meta {
    font-size: 0.65rem;
    color: #888;
    margin-top: 2px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>

<div class="container-fluid px-4 my-3">

  <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3 pb-2 border-bottom">
    <div class="d-flex align-items-center gap-2">
       <h5 class="mb-0 fw-normal"><i class="bi bi-folder2-open me-2"></i>Dateien</h5>
       <span class="badge bg-light text-secondary border fw-normal"><?= h($einheit) ?></span>
    </div>

    <div class="d-flex gap-2 align-items-center">
      <form method="get" class="d-flex gap-1">
        <div class="input-group input-group-sm">
          <span class="input-group-text bg-white border-end-0"><i class="bi bi-search"></i></span>
          <input type="text" name="search" class="form-control border-start-0 ps-0" placeholder="Suche..." value="<?= h($search) ?>" style="width: 150px;">
        </div>

        <select name="filter" class="form-select form-select-sm" style="width: 140px;" onchange="this.form.submit()">
          <option value="">Alle Ordner</option>
          <?php while ($k = $kat_result->fetch_assoc()): ?>
            <option value="<?= h($k['kategorie']) ?>" <?= $filter===$k['kategorie']?'selected':'' ?>><?= h($k['kategorie']) ?></option>
          <?php endwhile; ?>
        </select>

        <?php if ($search!=='' || $filter!==''): ?>
          <a href="dokumente.php" class="btn btn-sm btn-light border" title="Filter löschen">✖</a>
        <?php endif; ?>
      </form>

      <div class="vr mx-1"></div>

      <a href="?export=csv&<?= http_build_query(['search'=>$search,'filter'=>$filter]) ?>" class="btn btn-sm btn-light border" title="Export"><i class="bi bi-filetype-csv"></i></a>
      <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#uploadModal">
        <i class="bi bi-plus-lg"></i> Neu
      </button>
    </div>
  </div>

  <?= $meldung ?>

  <div class="explorer-container">

    <?php if ($dokumente->num_rows === 0): ?>
      <div class="w-100 text-center py-5 text-muted">
        <i class="bi bi-folder-x display-6 mb-2 d-block opacity-25"></i>
        <small>Dieser Ordner ist leer.</small>
      </div>
    <?php else: while ($d = $dokumente->fetch_assoc()): ?>
      <?php
        $id = (int)$d['id'];
        $fileHref = 'uploads/dokumente/' . $d['dateiname'];
        $ext = strtolower(pathinfo($d['dateiname'], PATHINFO_EXTENSION));

        // Icon Logik (Ähnlich wie Windows Farben)
        $iconClass = 'bi-file-earmark-text'; $colorStyle = 'color: #6c757d;'; // Grau

        if (in_array($ext, ['pdf'])) {
            $iconClass = 'bi-file-earmark-pdf-fill'; $colorStyle = 'color: #dc3545;'; // Rot
        } elseif (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
            $iconClass = 'bi-file-earmark-image-fill'; $colorStyle = 'color: #0d6efd;'; // Blau
        } elseif (in_array($ext, ['doc','docx','odt'])) {
            $iconClass = 'bi-file-earmark-word-fill'; $colorStyle = 'color: #0d6efd;';
        } elseif (in_array($ext, ['xls','xlsx','csv'])) {
            $iconClass = 'bi-file-earmark-excel-fill'; $colorStyle = 'color: #198754;'; // Grün
        } elseif (in_array($ext, ['zip','rar'])) {
            $iconClass = 'bi-file-earmark-zip-fill'; $colorStyle = 'color: #ffc107;'; // Gelb
        }
      ?>

      <div class="win-item" title="<?= h($d['anzeigename']) ?> (<?= h($d['kategorie']) ?>)">

        <a href="<?= h($fileHref) ?>" target="_blank" class="text-decoration-none">
          <i class="bi <?= $iconClass ?> win-icon" style="<?= $colorStyle ?>"></i>
          <div class="win-label"><?= h($d['anzeigename']) ?></div>
          <div class="win-meta"><?= fmtDate($d['hochgeladen_am']) ?></div>
        </a>

        <div class="dropdown">
          <button class="win-menu-btn" data-bs-toggle="dropdown" aria-expanded="false">
            <i class="bi bi-three-dots"></i>
          </button>
          <ul class="dropdown-menu shadow-sm" style="font-size: 0.9rem;">
            <li><h6 class="dropdown-header py-0"><?= h($d['anzeigename']) ?></h6></li>
            <li><hr class="dropdown-divider my-1"></li>
            <li><a class="dropdown-item" href="<?= h($fileHref) ?>" download><i class="bi bi-download me-2 text-muted"></i>Download</a></li>
            <li><button class="dropdown-item" data-bs-toggle="modal" data-bs-target="#editModal<?= $id ?>"><i class="bi bi-pencil me-2 text-muted"></i>Eigenschaften</button></li>
            <li><hr class="dropdown-divider my-1"></li>
            <li>
              <form method="post" class="d-inline" onsubmit="return confirm('Datei unwiderruflich löschen?');">
                <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                <input type="hidden" name="delete_id" value="<?= $id ?>">
                <button class="dropdown-item text-danger"><i class="bi bi-trash me-2"></i>Löschen</button>
              </form>
            </li>
          </ul>
        </div>

      </div>

      <div class="modal fade" id="editModal<?= $id ?>" tabindex="-1">
        <div class="modal-dialog modal-sm">
          <form method="post" class="modal-content">
            <div class="modal-header py-2">
              <h6 class="modal-title">Eigenschaften</h6>
              <button type="button" class="btn-close small" 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-2">
                <label class="form-label small mb-1">Name</label>
                <input type="text" name="edit_anzeigename" class="form-control form-control-sm" value="<?= h($d['anzeigename']) ?>" required>
              </div>
              <div class="mb-2">
                <label class="form-label small mb-1">Kategorie</label>
                <select name="edit_kategorie" class="form-select form-select-sm" 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 small mb-1">Barcode</label>
                <input type="text" name="edit_barcode" class="form-control form-control-sm" value="<?= h($d['barcode']) ?>">
              </div>
            </div>
            <div class="modal-footer py-1">
              <button class="btn btn-sm btn-primary">Speichern</button>
            </div>
          </form>
        </div>
      </div>

    <?php endwhile; endif; ?>
  </div>
</div>

<div class="modal fade" id="uploadModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="post" enctype="multipart/form-data" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Datei hinzufügen</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" placeholder="Wie soll die Datei heißen?" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Kategorie</label>
          <select name="kategorie" class="form-select" required>
            <option value="">– 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>
      </div>
    </form>
  </div>
</div>

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