<?php
// it_passwords.php – Passwortverwaltung (ähnlicher Aufbau wie it_assets.php)
ob_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

$user_id      = (int)$_SESSION['user_id'];
$user_einheit = $_SESSION['einheit'] ?? '';
$user_rechte  = (int)($_SESSION['is_admin'] ?? 0); // 0=Standard, >=1 darf löschen

if ($user_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 bind_params(mysqli_stmt $stmt, string $types, array &$params){
    $a = [$types];
    foreach($params as $k=>$_){ $a[] = &$params[$k]; }
    call_user_func_array([$stmt, 'bind_param'], $a);
}

// =====================================================================
//  Einfache Verschlüsselung der Passwörter (bitte Schlüssel anpassen!)
// =====================================================================
const PW_CRYPT_KEY = 'HIER_EINEN_LANGEN_GEHEIMEN_KEY_EINTRAGEN_UND_ANPASSEN!!!';

function pw_encrypt(string $plain): string {
    $plain = (string)$plain;
    if ($plain === '') return '';
    $key = hash('sha256', PW_CRYPT_KEY, true);
    $iv  = random_bytes(16);
    $cipher = openssl_encrypt($plain, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    if ($cipher === false) return '';
    return base64_encode($iv . $cipher);
}

function pw_decrypt(string $blob): string {
    $blob = (string)$blob;
    if ($blob === '') return '';
    $data = base64_decode($blob, true);
    if ($data === false || strlen($data) <= 16) return '';
    $iv     = substr($data, 0, 16);
    $cipher = substr($data, 16);
    $key    = hash('sha256', PW_CRYPT_KEY, true);
    $plain  = openssl_decrypt($cipher, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return $plain === false ? '' : $plain;
}

$meldung = '';

// ---------- Kameraden-Liste für Dropdown "zugewiesen_an" ----------
$kameradenList = [];
$stKm = $conn->prepare("
    SELECT id, vorname, nachname, spindnr
    FROM kameraden
    WHERE einheit = ? AND (archiv = '' OR archiv IS NULL)
    ORDER BY nachname, vorname
");
$stKm->bind_param("s", $user_einheit);
$stKm->execute();
$rKm = $stKm->get_result();
while ($km = $rKm->fetch_assoc()) {
    $kameradenList[] = $km;
}
$stKm->close();

// ---------- Eintrag löschen (nur eigene Einheit + Rechte) ----------
if (isset($_GET['delete']) && is_numeric($_GET['delete']) && $user_rechte >= 1) {
  $delId = (int)$_GET['delete'];
  $st = $conn->prepare("DELETE FROM it_passwords WHERE id = ? AND einheit = ?");
  $st->bind_param("is", $delId, $user_einheit);
  if ($st->execute() && $st->affected_rows > 0) {
    $meldung = "<div class='alert alert-success'>🗑️ Eintrag wurde gelöscht.</div>";
  } else {
    $meldung = "<div class='alert alert-danger'>❌ Fehler beim Löschen oder keine Berechtigung.</div>";
  }
}

// ---------- Neuen Passwort-Eintrag speichern ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pw_speichern'])) {

  $system_name   = trim($_POST['system_name'] ?? '');
  $kategorie     = trim($_POST['kategorie'] ?? '');
  $url           = trim($_POST['url'] ?? '');
  $username      = trim($_POST['username'] ?? '');
  $password_plain= trim($_POST['password_plain'] ?? '');
  $zugewiesen_an = trim($_POST['zugewiesen_an'] ?? '');
  $beschreibung  = trim($_POST['beschreibung'] ?? '');

  if ($system_name === '') {
    $meldung = "<div class='alert alert-danger'>❌ Bitte mindestens System-/Kontoname ausfüllen.</div>";
  } else {

    $password_enc = pw_encrypt($password_plain);

    $st = $conn->prepare("
        INSERT INTO it_passwords
          (einheit, system_name, kategorie, url, username, password_enc,
           zugewiesen_an, beschreibung)
        VALUES (?,?,?,?,?,?,?,?)
    ");
    $st->bind_param(
      "ssssssss",
      $user_einheit,
      $system_name,
      $kategorie,
      $url,
      $username,
      $password_enc,
      $zugewiesen_an,
      $beschreibung
    );

    $meldung = $st->execute()
      ? "<div class='alert alert-success'>✅ Zugang wurde gespeichert.</div>"
      : "<div class='alert alert-danger'>❌ Fehler beim Speichern.</div>";
  }
}

// ---------- Eintrag bearbeiten ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pw_update'])) {

  $id            = (int)($_POST['id'] ?? 0);
  $system_name   = trim($_POST['system_name_edit'] ?? '');
  $kategorie     = trim($_POST['kategorie_edit'] ?? '');
  $url           = trim($_POST['url_edit'] ?? '');
  $username      = trim($_POST['username_edit'] ?? '');
  $password_plain= trim($_POST['password_plain_edit'] ?? '');
  $zugewiesen_an = trim($_POST['zugewiesen_an_edit'] ?? '');
  $beschreibung  = trim($_POST['beschreibung_edit'] ?? '');

  if ($id > 0 && $system_name !== '') {

    // Passwort nur aktualisieren, wenn etwas eingegeben wurde
    if ($password_plain !== '') {
        $password_enc = pw_encrypt($password_plain);
        $st = $conn->prepare("
            UPDATE it_passwords
            SET system_name = ?, kategorie = ?, url = ?, username = ?,
                password_enc = ?, zugewiesen_an = ?, beschreibung = ?
            WHERE id = ? AND einheit = ?
        ");
        $st->bind_param(
          "sssssssis",
          $system_name,
          $kategorie,
          $url,
          $username,
          $password_enc,
          $zugewiesen_an,
          $beschreibung,
          $id,
          $user_einheit
        );
    } else {
        $st = $conn->prepare("
            UPDATE it_passwords
            SET system_name = ?, kategorie = ?, url = ?, username = ?,
                zugewiesen_an = ?, beschreibung = ?
            WHERE id = ? AND einheit = ?
        ");
        $st->bind_param(
          "ssssssis",
          $system_name,
          $kategorie,
          $url,
          $username,
          $zugewiesen_an,
          $beschreibung,
          $id,
          $user_einheit
        );
    }

    if ($st->execute() && $st->affected_rows >= 0) {
      $meldung = "<div class='alert alert-success'>💾 Änderungen gespeichert.</div>";
    } else {
      $meldung = "<div class='alert alert-warning'>ℹ️ Keine Änderungen oder Fehler beim Speichern.</div>";
    }
  } else {
    $meldung = "<div class='alert alert-danger'>❌ Bitte System-/Kontoname ausfüllen.</div>";
  }
}

// ---------- Filter ----------
$search   = trim($_GET['search'] ?? '');
$f_kat    = trim($_GET['kategorie'] ?? '');

// Kategorien (nur eigene Einheit)
$katList = [];
$stK = $conn->prepare("
    SELECT kategorie, COUNT(*) cnt
    FROM it_passwords
    WHERE einheit = ?
    GROUP BY kategorie
    ORDER BY kategorie
");
$stK->bind_param("s", $user_einheit);
$stK->execute();
$rK = $stK->get_result();
while($row = $rK->fetch_assoc()){ $katList[] = $row; }

// Dynamic WHERE
$where  = "einheit = ?";
$types  = "s";
$params = [$user_einheit];

if ($search !== '') {
  $like = '%'.$search.'%';
  $where .= " AND (
      system_name LIKE ?
      OR kategorie LIKE ?
      OR url LIKE ?
      OR username LIKE ?
      OR zugewiesen_an LIKE ?
  )";
  for($i=0;$i<5;$i++){ $params[] = $like; $types .= 's'; }
}
if ($f_kat !== '') {
  $where .= " AND kategorie = ?";
  $params[] = $f_kat; $types .= 's';
}

// ---------- KPIs ----------
$sqlKpi = "
    SELECT
      COUNT(*) AS cnt,
      COUNT(DISTINCT system_name) AS systems,
      COUNT(DISTINCT kategorie) AS cats
    FROM it_passwords
    WHERE $where
";
$stKpi = $conn->prepare($sqlKpi);
bind_params($stKpi, $types, $params);
$stKpi->execute();
$K = $stKpi->get_result()->fetch_assoc() ?: ['cnt'=>0,'systems'=>0,'cats'=>0];

// ---------- Liste ----------
$whereList  = $where;
$typesList  = $types;
$paramsList = $params;

$sqlList = "
    SELECT *
    FROM it_passwords
    WHERE $whereList
    ORDER BY kategorie, system_name, username
";
$stList = $conn->prepare($sqlList);
bind_params($stList, $typesList, $paramsList);
$stList->execute();
$passwords = $stList->get_result();
?>
<style>
  .kpi-card{border:1px solid #eee;border-radius:14px;padding:16px;background:#fff}
  .kpi-val{font-size:1.6rem;font-weight:700}
  .kpi-sub{font-size:.9rem;color:#6c757d}
  .toolbar .btn, .toolbar .form-control, .toolbar .form-select{ height:38px }
  .tab-badge{font-size:.75rem}
  .pw-dot{letter-spacing:2px;}
</style>

<div class="container my-5">
  <!-- Toolbar -->
  <div class="d-flex flex-wrap justify-content-between align-items-end gap-2 mb-3">
    <div>
      <h2 class="mb-1">Passwortverwaltung</h2>
      <div class="text-muted">Einheit: <span class="badge text-bg-secondary"><?= h($user_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: System / URL / Nutzer / Person"
               value="<?= h($search) ?>">

        <select name="kategorie" class="form-select">
          <option value="">Alle Kategorien</option>
          <?php foreach($katList as $k): ?>
            <option value="<?= h($k['kategorie']) ?>" <?= $f_kat===$k['kategorie']?'selected':'' ?>>
              <?= h($k['kategorie']) ?>
            </option>
          <?php endforeach; ?>
        </select>

        <button class="btn btn-outline-primary">Anwenden</button>
        <?php if ($search!=='' || $f_kat!==''): ?>
          <a href="it_passwords.php" class="btn btn-outline-secondary">Zurücksetzen</a>
        <?php endif; ?>
      </form>

      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#pwModal">
        ➕ Zugang hinzufügen
      </button>
    </div>
  </div>

  <?= $meldung ?>

  <!-- KPIs -->
  <div class="row g-3 mt-1 mb-4">
    <div class="col-6 col-md-4">
      <div class="kpi-card">
        <div class="kpi-sub">Einträge gesamt</div>
        <div class="kpi-val"><?= (int)$K['cnt'] ?></div>
      </div>
    </div>
    <div class="col-6 col-md-4">
      <div class="kpi-card">
        <div class="kpi-sub">Systeme</div>
        <div class="kpi-val"><?= (int)$K['systems'] ?></div>
      </div>
    </div>
    <div class="col-6 col-md-4">
      <div class="kpi-card">
        <div class="kpi-sub">Kategorien</div>
        <div class="kpi-val"><?= (int)$K['cats'] ?></div>
      </div>
    </div>
  </div>

  <!-- Tabs je Kategorie -->
  <ul class="nav nav-tabs mb-3" role="tablist">
    <?php
      $sumCnt = 0; foreach($katList as $x){ $sumCnt += (int)$x['cnt']; }
      $queryAll = http_build_query(['search'=>$search,'kategorie'=>'']);
    ?>
    <li class="nav-item" role="presentation">
      <a class="nav-link <?= $f_kat===''?'active':'' ?>" href="?<?= $queryAll ?>">
        Alle
        <span class="badge rounded-pill text-bg-light tab-badge"><?= $sumCnt ?></span>
      </a>
    </li>
    <?php foreach($katList as $k): ?>
      <li class="nav-item" role="presentation">
        <a class="nav-link <?= $f_kat===$k['kategorie']?'active':'' ?>"
           href="?<?= http_build_query(['search'=>$search,'kategorie'=>$k['kategorie']]) ?>">
          <?= h($k['kategorie']) ?>
          <span class="badge rounded-pill text-bg-light tab-badge"><?= (int)$k['cnt'] ?></span>
        </a>
      </li>
    <?php endforeach; ?>
  </ul>

  <!-- Tabelle -->
  <div class="card shadow-sm">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>System / Konto</th>
            <th>URL</th>
            <th>Benutzername</th>
            <th>Passwort</th>
            <th>Zugewiesen an</th>
            <th style="width:80px;" class="text-end"></th>
          </tr>
        </thead>
        <tbody>
          <?php if ($passwords->num_rows === 0): ?>
            <tr>
              <td colspan="6" class="text-center text-muted py-4">
                Keine Einträge gefunden.
              </td>
            </tr>
          <?php else: while($row = $passwords->fetch_assoc()):
              $pwPlain = pw_decrypt($row['password_enc']);
          ?>
            <tr>
              <td>
                <div class="fw-semibold"><?= h($row['system_name']) ?></div>
                <?php if ($row['kategorie']): ?>
                  <div class="text-muted small"><?= h($row['kategorie']) ?></div>
                <?php endif; ?>
                <?php if ($row['beschreibung']): ?>
                  <div class="text-muted small"><?= nl2br(h($row['beschreibung'])) ?></div>
                <?php endif; ?>
              </td>
              <td>
                <?php if ($row['url']): ?>
                  <a href="<?= h($row['url']) ?>" target="_blank" rel="noopener">
                    <?= h($row['url']) ?>
                  </a>
                <?php else: ?>
                  <span class="text-muted">–</span>
                <?php endif; ?>
              </td>
              <td><?= h($row['username']) ?: '<span class="text-muted">–</span>' ?></td>
              <td>
                <?php if ($pwPlain !== ''): ?>
                  <div class="d-flex align-items-center gap-2">
                    <input type="password"
                           class="form-control form-control-sm w-auto"
                           style="max-width: 160px;"
                           value="<?= h($pwPlain) ?>"
                           readonly
                           data-pw-field="1">
                    <button type="button"
                            class="btn btn-sm btn-outline-secondary"
                            onclick="togglePw(this)">👁</button>
                    <button type="button"
                            class="btn btn-sm btn-outline-primary"
                            onclick="copyPw(this)">📋</button>
                  </div>
                <?php else: ?>
                  <span class="text-muted">kein Passwort hinterlegt</span>
                <?php endif; ?>
              </td>
              <td><?= h($row['zugewiesen_an']) ?: '<span class="text-muted">–</span>' ?></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="#"
                       data-bs-toggle="modal"
                       data-bs-target="#editModal"
                       data-id="<?= (int)$row['id'] ?>"
                       data-system="<?= h($row['system_name']) ?>"
                       data-kategorie="<?= h($row['kategorie']) ?>"
                       data-url="<?= h($row['url']) ?>"
                       data-username="<?= h($row['username']) ?>"
                       data-zugewiesen="<?= h($row['zugewiesen_an']) ?>"
                       data-beschreibung="<?= h($row['beschreibung']) ?>"
                    >Bearbeiten</a>

                    <?php if ($user_rechte >= 1): ?>
                      <div class="dropdown-divider"></div>
                      <a class="dropdown-item text-danger"
                         href="?<?= http_build_query([
                           'delete'=>(int)$row['id'],
                           'search'=>$search,
                           'kategorie'=>$f_kat
                         ]) ?>"
                         onclick="return confirm('❗ Diesen Zugang wirklich löschen?');">
                        Löschen
                      </a>
                    <?php endif; ?>
                  </div>
                </div>
              </td>
            </tr>
          <?php endwhile; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal: Zugang hinzufügen -->
<div class="modal fade" id="pwModal" tabindex="-1" aria-labelledby="pwModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="pwModalLabel">Zugang hinzufügen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">System / Kontoname *</label>
            <input name="system_name" class="form-control" required placeholder="z. B. Hero, Nextcloud, Router">
          </div>
          <div class="col-md-6">
            <label class="form-label">Kategorie</label>
            <input name="kategorie" class="form-control" placeholder="z. B. Cloud, Netzwerk, Admin">
          </div>
          <div class="col-md-6">
            <label class="form-label">URL</label>
            <input name="url" class="form-control" placeholder="https://…">
          </div>
          <div class="col-md-6">
            <label class="form-label">Benutzername</label>
            <input name="username" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Passwort</label>
            <input name="password_plain" class="form-control" type="text" autocomplete="new-password">
          </div>
          <div class="col-md-6">
            <label class="form-label">Zugewiesen an</label>
            <select name="zugewiesen_an" class="form-select">
              <option value="">– nicht zugewiesen –</option>
              <?php foreach ($kameradenList as $km):
                  $label = trim($km['vorname'].' '.$km['nachname']);
                  $spind = trim((string)$km['spindnr']);
                  $text  = $label . ($spind !== '' ? ' (Spind '.$spind.')' : '');
              ?>
                <option value="<?= h($label) ?>"><?= h($text) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-12">
            <label class="form-label">Beschreibung / Hinweise</label>
            <textarea name="beschreibung" class="form-control" rows="3"
                      placeholder="z. B. nur für Admins, 2FA aktiv, Ablaufdatum…"></textarea>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="pw_speichern" class="btn btn-primary">Speichern</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal: Zugang bearbeiten -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editModalLabel">Zugang bearbeiten</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="edit_id">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">System / Kontoname *</label>
            <input name="system_name_edit" id="edit_system" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Kategorie</label>
            <input name="kategorie_edit" id="edit_kategorie" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">URL</label>
            <input name="url_edit" id="edit_url" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Benutzername</label>
            <input name="username_edit" id="edit_username" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Neues Passwort (optional)</label>
            <input name="password_plain_edit" id="edit_password" class="form-control" type="text"
                   autocomplete="new-password"
                   placeholder="leer lassen = Passwort bleibt unverändert">
          </div>
          <div class="col-md-6">
            <label class="form-label">Zugewiesen an</label>
            <select name="zugewiesen_an_edit" id="edit_zugewiesen" class="form-select">
              <option value="">– nicht zugewiesen –</option>
              <?php foreach ($kameradenList as $km):
                  $label = trim($km['vorname'].' '.$km['nachname']);
                  $spind = trim((string)$km['spindnr']);
                  $text  = $label . ($spind !== '' ? ' (Spind '.$spind.')' : '');
              ?>
                <option value="<?= h($label) ?>"><?= h($text) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-12">
            <label class="form-label">Beschreibung / Hinweise</label>
            <textarea name="beschreibung_edit" id="edit_beschreibung" class="form-control" rows="3"></textarea>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="pw_update" class="btn btn-primary">Änderungen speichern</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
      </div>
    </form>
  </div>
</div>

<script>
// Toggle Passwort im Tabellenfeld
function togglePw(btn){
  const input = btn.parentElement.querySelector('input[data-pw-field]');
  if (!input) return;
  if (input.type === 'password') {
    input.type = 'text';
    btn.textContent = '🙈';
  } else {
    input.type = 'password';
    btn.textContent = '👁';
  }
}

function copyPw(btn){
  const input = btn.parentElement.querySelector('input[data-pw-field]');
  if (!input) return;
  input.type = 'text';
  input.select();
  document.execCommand('copy');
  input.type = 'password';
  btn.textContent = '✅';
  setTimeout(()=>{ btn.textContent = '📋'; }, 1000);
}

// Füllt den Bearbeiten-Modal
document.addEventListener('show.bs.modal', function (ev) {
  if (ev.target && ev.target.id === 'editModal') {
    const btn = ev.relatedTarget;
    if (!btn) return;

    const id           = btn.getAttribute('data-id');
    const system       = btn.getAttribute('data-system') || '';
    const kategorie    = btn.getAttribute('data-kategorie') || '';
    const url          = btn.getAttribute('data-url') || '';
    const username     = btn.getAttribute('data-username') || '';
    const zugewiesen   = btn.getAttribute('data-zugewiesen') || '';
    const beschreibung = btn.getAttribute('data-beschreibung') || '';

    document.getElementById('edit_id').value             = id;
    document.getElementById('edit_system').value         = system;
    document.getElementById('edit_kategorie').value      = kategorie;
    document.getElementById('edit_url').value            = url;
    document.getElementById('edit_username').value       = username;
    document.getElementById('edit_beschreibung').value   = beschreibung;
    document.getElementById('edit_password').value       = '';

    const selZug = document.getElementById('edit_zugewiesen');
    if (selZug) {
      let found = false;
      Array.from(selZug.options).forEach(o => {
        if (o.value === zugewiesen) {
          o.selected = true;
          found = true;
        }
      });
      if (!found && zugewiesen !== '') {
        const opt = new Option(zugewiesen + ' (alt)', zugewiesen, true, true);
        selZug.add(opt);
      }
    }
  }
});
</script>

<?php
include 'includes/footer.php';
if (ob_get_level() > 0) {
    ob_end_flush();
}
?>
