<?php
/*******************************************************
 * adressen.php – Verwaltung von Adressen
 * - Liste mit Suche/Filter
 * - Neu anlegen & Bearbeiten (Modal)
 * - Löschen (Bestätigungs-Modal)
 * - CSV-Export
 *******************************************************/
ob_start();
session_start();

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

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

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

// ─────────────────────────────────────────────────────────────
// Flash-Messages
if (!isset($_SESSION['flash'])) $_SESSION['flash'] = [];
function flash_add($type,$msg){ $_SESSION['flash'][]=['t'=>$type,'m'=>$msg]; }
function flash_render(){
  if (empty($_SESSION['flash'])) return;
  echo "<div class='container mt-3'>";
  foreach($_SESSION['flash'] as $f){
    $map=['success'=>'success','error'=>'danger','warn'=>'warning','info'=>'info'];
    $cls=$map[$f['t']]??'secondary';
    echo "<div class='alert alert-{$cls} d-flex align-items-center gap-2 mb-2'>{$f['m']}</div>";
  }
  echo "</div>";
  $_SESSION['flash']=[];
}

// ─────────────────────────────────────────────────────────────
// CSRF
if (empty($_SESSION['csrf_token'])) {
  $_SESSION['csrf_token'] = bin2hex(random_bytes(24));
}
$CSRF = $_SESSION['csrf_token'];
function csrf_check($t){ return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], (string)$t); }

// ─────────────────────────────────────────────────────────────
// Aktionen: Speichern (neu/ändern), Löschen, CSV
if ($_SERVER['REQUEST_METHOD']==='POST') {
  $action = $_POST['action'] ?? '';
  if (!csrf_check($_POST['csrf'] ?? '')) {
    flash_add('error','❌ Sicherheitsprüfung fehlgeschlagen (CSRF).');
    header('Location: '.$_SERVER['PHP_SELF']); exit;
  }

  if ($action === 'save') {
    $id    = (int)($_POST['id'] ?? 0);
    $bez   = trim($_POST['bezeichnung'] ?? '');
    $str   = trim($_POST['strasse'] ?? '');
    $plz   = trim($_POST['plz'] ?? '');
    $ort   = trim($_POST['ort'] ?? '');
    $hin   = trim($_POST['hinweis'] ?? '');

    if ($bez === '') {
      flash_add('error','Bitte mindestens <strong>Bezeichnung</strong> angeben.');
      header('Location: '.$_SERVER['PHP_SELF']); exit;
    }

    if ($id > 0) {
      $stmt = $conn->prepare("UPDATE adressen SET bezeichnung=?, strasse=?, plz=?, ort=?, hinweis=? WHERE id=?");
      $stmt->bind_param('sssssi', $bez, $str, $plz, $ort, $hin, $id);
      $ok = $stmt->execute();
      $ok ? flash_add('success','✅ Adresse aktualisiert.') : flash_add('error','❌ Konnte nicht aktualisiert werden.');
    } else {
      $stmt = $conn->prepare("INSERT INTO adressen (bezeichnung, strasse, plz, ort, hinweis) VALUES (?,?,?,?,?)");
      $stmt->bind_param('sssss', $bez, $str, $plz, $ort, $hin);
      $ok = $stmt->execute();
      $ok ? flash_add('success','✅ Adresse angelegt.') : flash_add('error','❌ Konnte nicht angelegt werden.');
    }
    header('Location: '.$_SERVER['PHP_SELF']); exit;
  }

  if ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id>0) {
      $stmt = $conn->prepare("DELETE FROM adressen WHERE id=?");
      $stmt->bind_param('i',$id);
      $stmt->execute();
      if ($stmt->affected_rows>0) {
        flash_add('success','🗑️ Adresse gelöscht.');
      } else {
        flash_add('warn','ℹ️ Adresse nicht gefunden.');
      }
    }
    header('Location: '.$_SERVER['PHP_SELF']); exit;
  }
}

// CSV-Export
if (isset($_GET['export']) && $_GET['export']==='csv') {
  $filename = 'adressen_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, ['ID','Bezeichnung','Straße','PLZ','Ort','Hinweis']);

  $q = trim($_GET['q'] ?? '');
  if ($q!=='') {
    $like = "%$q%";
    $st = $conn->prepare("SELECT id,bezeichnung,strasse,plz,ort,hinweis FROM adressen
                          WHERE bezeichnung LIKE ? OR strasse LIKE ? OR plz LIKE ? OR ort LIKE ? OR hinweis LIKE ?
                          ORDER BY bezeichnung ASC");
    $st->bind_param('sssss',$like,$like,$like,$like,$like);
  } else {
    $st = $conn->prepare("SELECT id,bezeichnung,strasse,plz,ort,hinweis FROM adressen ORDER BY bezeichnung ASC");
  }
  $st->execute(); $res=$st->get_result();
  while($r=$res->fetch_assoc()){
    fputcsv($out, [$r['id'],$r['bezeichnung'],$r['strasse'],$r['plz'],$r['ort'],$r['hinweis']]);
  }
  fclose($out); exit;
}

// ─────────────────────────────────────────────────────────────
// Suche / Liste
$q = trim($_GET['q'] ?? '');
if ($q!=='') {
  $like = "%$q%";
  $st = $conn->prepare("SELECT * FROM adressen
                         WHERE bezeichnung LIKE ? OR strasse LIKE ? OR plz LIKE ? OR ort LIKE ? OR hinweis LIKE ?
                         ORDER BY bezeichnung ASC");
  $st->bind_param('sssss',$like,$like,$like,$like,$like);
} else {
  $st = $conn->prepare("SELECT * FROM adressen ORDER BY bezeichnung ASC");
}
$st->execute();
$list = $st->get_result();

// ─────────────────────────────────────────────────────────────
// UI
flash_render();
?>
<div class="container my-4">
  <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
    <div>
      <h2 class="mb-0">📇 Adressen</h2>
      <div class="text-muted small">Verwalte Empfänger/Zieladressen für Lieferscheine & Dokumente.</div>
    </div>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-secondary" href="?export=csv<?= $q!=='' ? '&q='.urlencode($q) : '' ?>">
        <i class="bi bi-download"></i> CSV Export
      </a>
      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#modalEdit"
              onclick="ADR.openCreate()">
        <i class="bi bi-plus-circle"></i> Neue Adresse
      </button>
    </div>
  </div>

  <!-- Suche -->
  <div class="card shadow-sm mt-3">
    <div class="card-body">
      <form method="get" class="row g-2 align-items-end">
        <div class="col-md-8">
          <label class="form-label">Suche</label>
          <input type="text" name="q" class="form-control" value="<?= h($q) ?>" placeholder="Bezeichnung, Straße, PLZ, Ort, Hinweis">
        </div>
        <div class="col-md-4 d-flex gap-2">
          <button class="btn btn-primary flex-grow-1"><i class="bi bi-search"></i> Anwenden</button>
          <a class="btn btn-outline-secondary" href="adressen.php"><i class="bi bi-x-circle"></i> Zurücksetzen</a>
        </div>
      </form>
    </div>
  </div>

  <!-- Liste -->
  <div class="card shadow-sm mt-3">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>Bezeichnung</th>
            <th>Straße</th>
            <th style="width:90px;">PLZ</th>
            <th>Ort</th>
            <th>Hinweis</th>
            <th class="text-end" style="width:160px;">Aktion</th>
          </tr>
        </thead>
        <tbody>
        <?php if ($list->num_rows === 0): ?>
          <tr><td colspan="6" class="text-center text-muted py-4">Keine Adressen gefunden.</td></tr>
        <?php else: while($r=$list->fetch_assoc()): ?>
          <tr>
            <td><strong><?= h($r['bezeichnung'] ?? '') ?></strong></td>
            <td><?= h($r['strasse'] ?? '') ?></td>
            <td><?= h($r['plz'] ?? '') ?></td>
            <td><?= h($r['ort'] ?? '') ?></td>
            <td class="text-truncate" style="max-width: 320px;"><?= h($r['hinweis'] ?? '') ?></td>
            <td class="text-end">
              <div class="btn-group">
                <button class="btn btn-sm btn-outline-primary"
                        data-bs-toggle="modal" data-bs-target="#modalEdit"
                        onclick='ADR.openEdit(<?= (int)$r["id"] ?>, <?= json_encode($r, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>)'>
                  <i class="bi bi-pencil-square"></i> Bearbeiten
                </button>
                <button class="btn btn-sm btn-outline-danger"
                        data-bs-toggle="modal" data-bs-target="#modalDelete"
                        onclick='ADR.openDelete(<?= (int)$r["id"] ?>, <?= json_encode((string)($r["bezeichnung"] ?? "Adresse")) ?>)'>
                  <i class="bi bi-trash"></i> Löschen
                </button>
              </div>
            </td>
          </tr>
        <?php endwhile; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal: Neu/Bearbeiten -->
<div class="modal fade" id="modalEdit" tabindex="-1" aria-labelledby="modalEditLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <form class="modal-content" method="post" action="">
      <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
      <input type="hidden" name="action" value="save">
      <input type="hidden" name="id" id="form-id" value="">
      <div class="modal-header">
        <h5 class="modal-title" id="modalEditLabel"><i class="bi bi-geo-alt"></i> Adresse</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schließen"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Bezeichnung *</label>
            <input type="text" class="form-control" name="bezeichnung" id="form-bezeichnung" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Straße</label>
            <input type="text" class="form-control" name="strasse" id="form-strasse" placeholder="z. B. Musterweg 1">
          </div>
          <div class="col-md-3">
            <label class="form-label">PLZ</label>
            <input type="text" class="form-control" name="plz" id="form-plz" maxlength="10">
          </div>
          <div class="col-md-9">
            <label class="form-label">Ort</label>
            <input type="text" class="form-control" name="ort" id="form-ort">
          </div>
          <div class="col-12">
            <label class="form-label">Hinweis</label>
            <textarea class="form-control" name="hinweis" id="form-hinweis" rows="3" placeholder="z. B. Tor 3, Ansprechpartner, Öffnungszeiten ..."></textarea>
            <div class="form-text">Wird in der Adressvorschau auf dem Lieferschein angezeigt.</div>
          </div>
        </div>
      </div>
      <div class="modal-footer justify-content-between">
        <div class="text-muted small"><span class="text-danger">*</span> Pflichtfelder</div>
        <div>
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Abbrechen</button>
          <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Speichern</button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- Modal: Löschen -->
<div class="modal fade" id="modalDelete" tabindex="-1" aria-labelledby="modalDeleteLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <form class="modal-content" method="post" action="">
      <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
      <input type="hidden" name="action" value="delete">
      <input type="hidden" name="id" id="delete-id" value="">
      <div class="modal-header">
        <h5 class="modal-title" id="modalDeleteLabel">Adresse löschen?</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schließen"></button>
      </div>
      <div class="modal-body">
        <p>Möchtest du die Adresse <strong id="delete-label">–</strong> wirklich löschen?</p>
        <p class="text-muted small mb-0"><i class="bi bi-exclamation-triangle"></i> Dieser Vorgang kann nicht rückgängig gemacht werden.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Abbrechen</button>
        <button type="submit" class="btn btn-danger"><i class="bi bi-trash"></i> Löschen</button>
      </div>
    </form>
  </div>
</div>

<script>
// Modale Helper
const ADR = {
  openCreate(){
    document.getElementById('modalEditLabel').textContent = 'Neue Adresse anlegen';
    document.getElementById('form-id').value = '';
    document.getElementById('form-bezeichnung').value = '';
    document.getElementById('form-strasse').value = '';
    document.getElementById('form-plz').value = '';
    document.getElementById('form-ort').value = '';
    document.getElementById('form-hinweis').value = '';
  },
  openEdit(id, row){
    document.getElementById('modalEditLabel').textContent = 'Adresse bearbeiten';
    document.getElementById('form-id').value = id;
    document.getElementById('form-bezeichnung').value = (row.bezeichnung ?? '');
    document.getElementById('form-strasse').value = (row.strasse ?? '');
    document.getElementById('form-plz').value = (row.plz ?? '');
    document.getElementById('form-ort').value = (row.ort ?? '');
    document.getElementById('form-hinweis').value = (row.hinweis ?? '');
  },
  openDelete(id, label){
    document.getElementById('delete-id').value = id;
    document.getElementById('delete-label').textContent = label || '–';
  }
};
window.ADR = ADR;
</script>

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