<?php
// psa.php – PSA Verwaltung (Standard Design + Schwarze Tab-Schriften)
ob_start();
session_start();

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

/* -------------------- Zugriff & Setup -------------------- */
$einheit = $_SESSION['einheit'] ?? '';
if (empty($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;
}

$meldung    = '';
$search     = trim($_GET['search'] ?? '');
$activeTab  = '';

$typen = ['Einsatzjacke', 'Einsatzhose', 'Einsatzhose AGT', 'Stiefel', 'Helm', 'Helmlampe'];

/* -------------------- Status-Helfer -------------------- */
function statusBadge(string $s): string {
    $sRaw = mb_strtolower(trim($s));
    if ($sRaw === 'einsatzbereit') return '<span class="badge bg-success-subtle text-success border border-success-subtle"><i class="bi bi-check-circle-fill me-1"></i>Einsatzbereit</span>';
    if ($sRaw === 'nicht einsatzbereit') return '<span class="badge bg-danger-subtle text-danger border border-danger-subtle"><i class="bi bi-x-circle-fill me-1"></i>Gesperrt</span>';
    return '<span class="badge bg-secondary-subtle text-secondary border border-secondary-subtle">'.htmlspecialchars($s).'</span>';
}

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

/* -------------------- Löschen -------------------- */
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $delId = (int)$_GET['delete'];
    $stmt = $conn->prepare("DELETE FROM psa_ausruestung WHERE id = ? AND einheit = ?");
    $stmt->bind_param("is", $delId, $einheit);
    if ($stmt->execute()) {
        $meldung = ($stmt->affected_rows > 0)
            ? "<div class='alert alert-success alert-dismissible fade show'>🗑️ Eintrag gelöscht.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>"
            : "<div class='alert alert-info alert-dismissible fade show'>ℹ️ Eintrag nicht gefunden.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
    }
}

/* -------------------- Hinzufügen -------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_psa'])) {
    $typ              = trim($_POST['typ'] ?? '');
    $hersteller       = trim($_POST['hersteller'] ?? '');
    $modell           = trim($_POST['modell'] ?? '');
    $groesse          = trim($_POST['groesse'] ?? '');
    $spindnr          = trim($_POST['spindnr'] ?? '');
    $id_code          = trim($_POST['id_code'] ?? '');
    $charge           = trim($_POST['charge'] ?? '');
    $herstellungsjahr = trim($_POST['herstellungsjahr'] ?? '');
    $status           = trim($_POST['status'] ?? 'Einsatzbereit');

    if ($typ && $hersteller && $modell) {
        $stmt = $conn->prepare("INSERT INTO psa_ausruestung (typ, hersteller, modell, groesse, spindnr, id_code, charge, herstellungsjahr, status, einheit) VALUES (?,?,?,?,?,?,?,?,?,?)");
        $stmt->bind_param("ssssssssss", $typ, $hersteller, $modell, $groesse, $spindnr, $id_code, $charge, $herstellungsjahr, $status, $einheit);
        $meldung = $stmt->execute()
            ? "<div class='alert alert-success alert-dismissible fade show'>✅ PSA gespeichert.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>"
            : "<div class='alert alert-danger alert-dismissible fade show'>❌ Fehler beim Speichern.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
    } else {
        $meldung = "<div class='alert alert-warning alert-dismissible fade show'>Bitte alle Pflichtfelder (*) ausfüllen.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
    }
}

/* -------------------- CSV Export -------------------- */
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $filename = 'psa_export_' . date('Y-m-d') . '.csv';
    header('Content-Type: text/csv; charset=utf-8');
    header("Content-Disposition: attachment; filename=\"$filename\"");
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Typ','Hersteller','Modell','Größe','Spind','Kamerad','ID-Code','Charge','Herstellungsjahr','Status','Einheit']);
    $like = '%' . $search . '%';
    $st = $conn->prepare("SELECT psa.*, k.vorname, k.nachname FROM psa_ausruestung psa LEFT JOIN kameraden k ON psa.spindnr = k.spindnr AND k.einheit = psa.einheit WHERE psa.einheit = ? AND (? = '' OR psa.id_code LIKE ?) ORDER BY psa.typ, CAST(psa.spindnr AS UNSIGNED), psa.id DESC");
    $st->bind_param('sss', $einheit, $search, $like);
    $st->execute();
    $res = $st->get_result();
    while ($r = $res->fetch_assoc()){
        fputcsv($out, [$r['typ'],$r['hersteller'],$r['modell'],$r['groesse'],$r['spindnr'],trim(($r['vorname']??'').' '.($r['nachname']??'')),$r['id_code'],$r['charge'],$r['herstellungsjahr'],$r['status'],$r['einheit']]);
    }
    fclose($out); exit;
}

/* -------------------- Logik: Aktiver Tab & Counts -------------------- */
if ($search !== '') {
    $stmtTab = $conn->prepare("SELECT typ FROM psa_ausruestung WHERE einheit = ? AND id_code LIKE ? LIMIT 1");
    $likeSearch = '%' . $search . '%';
    $stmtTab->bind_param("ss", $einheit, $likeSearch);
    $stmtTab->execute();
    if ($rowTab = $stmtTab->get_result()->fetch_assoc()) $activeTab = $rowTab['typ'];
}

$typeCounts = [];
$stc = $conn->prepare("SELECT typ, COUNT(*) as cnt FROM psa_ausruestung WHERE einheit = ? AND (? = '' OR id_code LIKE ?) GROUP BY typ");
$likeSearch = '%' . $search . '%';
$stc->bind_param('sss', $einheit, $search, $likeSearch);
$stc->execute();
$cr = $stc->get_result();
while ($c = $cr->fetch_assoc()) $typeCounts[$c['typ']] = (int)$c['cnt'];
?>

<style>
  /* --- Tab Design --- */

  /* Standard Zustand (Inaktiv) */
  .nav-tabs .nav-link {
      background-color: #f8f9fa; /* Hellgrauer Hintergrund */
      color: #000000 !important; /* SCHWARZE SCHRIFT ERZWINGEN */
      font-weight: 500;
      border: 1px solid #dee2e6;
      border-bottom: none;
      margin-right: 2px;
  }

  /* Hover Zustand */
  .nav-tabs .nav-link:hover {
      background-color: #e9ecef; /* Etwas dunkleres Grau */
      color: #000000 !important;
      border-color: #dee2e6;
  }

  /* Aktiver Zustand */
  .nav-tabs .nav-link.active {
      background-color: #ffffff !important; /* Weißer Hintergrund */
      color: #000000 !important; /* Schwarze Schrift */
      font-weight: 800; /* Extra Fett */
      border-color: #dee2e6 #dee2e6 #fff; /* Rahmen unten offen */
      border-top: 3px solid #0d6efd; /* Blauer Akzent oben */
  }

  /* Badge Styles in Tabs */
  .nav-tabs .nav-link .badge {
      background-color: #dee2e6;
      color: #000;
  }
  .nav-tabs .nav-link.active .badge {
      background-color: #0d6efd;
      color: #fff;
  }

  /* Container unter den Tabs */
  .tab-content-container {
      background: #fff;
      border: 1px solid #dee2e6;
      border-top: none;
      border-bottom-left-radius: 0.375rem;
      border-bottom-right-radius: 0.375rem;
      box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
  }

  /* Tabelle und Avatar */
  .avatar-circle {
      width: 32px; height: 32px;
      background-color: #e9ecef; color: #495057;
      border-radius: 50%;
      display: flex; align-items: center; justify-content: center;
      font-weight: 600; font-size: 0.75rem;
      margin-right: 8px;
  }
  .table-modern th {
      font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.5px;
      color: #6c757d; background: #f8f9fa; font-weight: 600;
      border-bottom: 2px solid #e9ecef;
  }
  .table-modern td {
      vertical-align: middle;
      border-bottom: 1px solid #f1f5f9;
      padding: 12px 8px;
      color: #212529;
  }
  .table-modern tr:hover { background-color: #f8f9fa; }
</style>

<div class="container my-5">

  <div class="d-flex flex-wrap justify-content-between align-items-end gap-3 mb-4">
    <div>
      <h2 class="fw-bold mb-1"><i class="bi bi-person-gear text-primary me-2"></i>PSA Verwaltung</h2>
      <div class="text-muted small">Einheit: <span class="badge bg-light text-secondary border"><?= h($einheit) ?></span></div>
    </div>

    <div class="d-flex flex-wrap gap-2">
      <form method="get" class="d-flex gap-2">
         <div class="input-group">
            <span class="input-group-text bg-white text-muted border-end-0"><i class="bi bi-search"></i></span>
            <input type="text" name="search" class="form-control border-start-0 ps-0" placeholder="ID-Code..." value="<?= h($search) ?>" style="max-width: 200px;">
         </div>
         <?php if ($search !== ''): ?>
            <a href="psa.php" class="btn btn-light border" title="Reset"><i class="bi bi-x-lg"></i></a>
         <?php endif; ?>
      </form>
      <div class="vr mx-1 d-none d-md-block"></div>
      <a href="?export=csv&search=<?= urlencode($search) ?>" class="btn btn-outline-secondary"><i class="bi bi-download"></i> CSV</a>
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#psaModal"><i class="bi bi-plus-lg"></i> Neu</button>
    </div>
  </div>

  <?= $meldung ?>

  <ul class="nav nav-tabs border-bottom-0" role="tablist">
    <?php foreach ($typen as $i => $typ):
      $isActive = ($typ === $activeTab) || ($i === 0 && $activeTab === '');
      $count    = $typeCounts[$typ] ?? 0;
    ?>
      <li class="nav-item">
        <a class="nav-link <?= $isActive ? 'active' : '' ?>" id="tab-<?= $i ?>" data-bs-toggle="tab" href="#tab-content-<?= $i ?>" role="tab">
          <?= h($typ) ?>
          <?php if($count > 0): ?>
            <span class="badge ms-1 rounded-pill"><?= $count ?></span>
          <?php endif; ?>
        </a>
      </li>
    <?php endforeach; ?>
  </ul>

  <div class="tab-content-container">
    <div class="tab-content">
      <?php foreach ($typen as $i => $typ):
        $isActive = ($typ === $activeTab) || ($i === 0 && $activeTab === '');
      ?>
        <div class="tab-pane fade <?= $isActive ? 'show active' : '' ?>" id="tab-content-<?= $i ?>" role="tabpanel">
          <?php
          $stmt = $conn->prepare("
            SELECT psa.*, k.vorname, k.nachname
              FROM psa_ausruestung psa
           LEFT JOIN kameraden k ON psa.spindnr = k.spindnr AND k.einheit = psa.einheit
             WHERE psa.typ = ? AND psa.einheit = ? AND (? = '' OR psa.id_code LIKE ?)
          ORDER BY CAST(psa.spindnr AS UNSIGNED), psa.id DESC
          ");
          $like = '%' . $search . '%';
          $stmt->bind_param("ssss", $typ, $einheit, $search, $like);
          $stmt->execute();
          $result = $stmt->get_result();
          ?>

          <?php if ($result->num_rows === 0): ?>
            <div class="text-center py-5">
              <i class="bi bi-inbox fs-1 text-light-emphasis"></i>
              <p class="text-muted mt-2">Keine PSA vom Typ "<?= h($typ) ?>" gefunden.</p>
              <?php if($search): ?><p class="small text-danger">Filter aktiv: "<?= h($search) ?>"</p><?php endif; ?>
            </div>
          <?php else: ?>
            <div class="table-responsive">
              <table class="table table-modern align-middle mb-0">
                <thead>
                  <tr>
                    <th class="ps-3">Ausrüstung</th>
                    <th>Größe / Details</th>
                    <th>Zugewiesen an</th>
                    <th>ID / Charge</th>
                    <th>Status</th>
                    <th class="text-end pe-3"></th>
                  </tr>
                </thead>
                <tbody>
                  <?php while ($row = $result->fetch_assoc()):
                    $name   = trim(($row['vorname'] ?? '').' '.($row['nachname'] ?? ''));
                    $initials = $name ? strtoupper(substr($row['vorname']??'',0,1).substr($row['nachname']??'',0,1)) : '?';
                  ?>
                    <tr>
                      <td class="ps-3">
                        <div class="fw-bold text-dark"><?= h($row['modell']) ?></div>
                        <div class="small text-muted"><?= h($row['hersteller']) ?></div>
                      </td>
                      <td>
                        <?php if($row['groesse']): ?>
                          <span class="badge bg-light text-dark border me-1"><?= h($row['groesse']) ?></span>
                        <?php endif; ?>
                        <?php if($row['herstellungsjahr']): ?>
                           <span class="small text-muted" title="Herstellungsjahr"><i class="bi bi-calendar"></i> <?= h($row['herstellungsjahr']) ?></span>
                        <?php endif; ?>
                      </td>
                      <td>
                        <?php if($row['spindnr']): ?>
                           <div class="d-flex align-items-center">
                             <div class="avatar-circle"><?= $initials ?></div>
                             <div style="line-height:1.2">
                                <div class="small fw-semibold text-dark"><?= $name ?: 'Unbekannt' ?></div>
                                <div class="small text-muted" style="font-size:0.7rem">Spind <?= h($row['spindnr']) ?></div>
                             </div>
                           </div>
                        <?php else: ?>
                           <span class="text-muted small fst-italic">Lagerbestand</span>
                        <?php endif; ?>
                      </td>
                      <td class="small">
                         <?php if($row['id_code']): ?>
                           <div class="font-monospace text-dark"><i class="bi bi-qr-code me-1 opacity-50"></i><?= h($row['id_code']) ?></div>
                         <?php endif; ?>
                         <?php if($row['charge']): ?>
                           <div class="text-muted">Charge: <?= h($row['charge']) ?></div>
                         <?php endif; ?>
                      </td>
                      <td><?= statusBadge($row['status']) ?></td>
                      <td class="text-end pe-3">
                        <div class="dropdown">
                          <button class="btn btn-sm btn-light rounded-circle shadow-sm" type="button" data-bs-toggle="dropdown">
                            <i class="bi bi-three-dots-vertical"></i>
                          </button>
                          <ul class="dropdown-menu dropdown-menu-end border-0 shadow">
                            <li><a class="dropdown-item" href="psa_edit.php?id=<?= (int)$row['id'] ?>"><i class="bi bi-pencil me-2 text-muted"></i> Bearbeiten</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                              <a class="dropdown-item text-danger" href="?delete=<?= (int)$row['id'] ?>&search=<?= urlencode($search) ?>" onclick="return confirm('Wirklich löschen?');">
                                <i class="bi bi-trash me-2"></i> Löschen
                              </a>
                            </li>
                          </ul>
                        </div>
                      </td>
                    </tr>
                  <?php endwhile; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>

<div class="modal fade" id="psaModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-plus-circle text-primary me-2"></i>Neue PSA erfassen</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-12"><h6 class="text-primary border-bottom pb-2 mb-0">Basisdaten</h6></div>

          <div class="col-md-4">
            <label class="form-label fw-semibold small">Typ *</label>
            <select name="typ" class="form-select" required>
              <option value="">– Wählen –</option>
              <?php foreach ($typen as $t): ?>
                <option><?= h($t) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label fw-semibold small">Hersteller *</label>
            <input type="text" name="hersteller" class="form-control" placeholder="z.B. Rosenbauer" required>
          </div>
          <div class="col-md-4">
            <label class="form-label fw-semibold small">Modell *</label>
            <input type="text" name="modell" class="form-control" placeholder="z.B. Fire Max 3" required>
          </div>

          <div class="col-12 mt-4"><h6 class="text-primary border-bottom pb-2 mb-0">Spezifikationen & Zuordnung</h6></div>

          <div class="col-md-3">
            <label class="form-label small">Größe</label>
            <input type="text" name="groesse" class="form-control" placeholder="z.B. 52 / L">
          </div>
          <div class="col-md-3">
            <label class="form-label small">Herstellungsjahr</label>
            <input type="number" name="herstellungsjahr" class="form-control" min="2000" max="<?= date('Y') ?>" placeholder="JJJJ">
          </div>
          <div class="col-md-3">
            <label class="form-label small">Charge</label>
            <input type="text" name="charge" class="form-control">
          </div>
          <div class="col-md-3">
             <label class="form-label small">Status</label>
             <select name="status" class="form-select bg-light">
               <option value="Einsatzbereit">Einsatzbereit</option>
               <option value="Nicht Einsatzbereit">Nicht Einsatzbereit</option>
             </select>
          </div>

          <div class="col-md-6">
            <label class="form-label small">ID-Code (Barcode/RFID)</label>
            <div class="input-group">
               <span class="input-group-text"><i class="bi bi-qr-code"></i></span>
               <input type="text" name="id_code" class="form-control" placeholder="Scannen oder tippen...">
            </div>
          </div>
          <div class="col-md-6">
            <label class="form-label small">Spindnummer</label>
            <div class="input-group">
               <span class="input-group-text"><i class="bi bi-person"></i></span>
               <input type="text" name="spindnr" class="form-control" placeholder="Nur Nummer eingeben">
            </div>
            <div class="form-text">Wird automatisch dem Kameraden zugeordnet.</div>
          </div>

        </div>
      </div>
      <div class="modal-footer bg-light">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
        <button type="submit" name="save_psa" class="btn btn-primary px-4">Speichern</button>
      </div>
    </form>
  </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
  const activeTab = <?= json_encode($activeTab, JSON_UNESCAPED_UNICODE) ?>;
  const typen = <?= json_encode($typen, JSON_UNESCAPED_UNICODE) ?>;
  const index = typen.indexOf(activeTab);
  if (index !== -1) {
    const triggerEl = document.querySelector(`#tab-${index}`);
    if (triggerEl) bootstrap.Tab.getOrCreateInstance(triggerEl).show();
  }
});
</script>

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