<?php
// admin/empfaenger/sperrliste.php
// Übersicht der Sperrliste inkl. Suche & CSV-Import

session_start();
require_once __DIR__ . '/../../includes/init.php';
require_once __DIR__ . '/../../auth/AuthController.php';

$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: ' . $adminLoginPath);
    exit;
}

$db = Database::getInstance();

$title = 'Sperrliste (Blacklist)';

// ------------------------------
// Helper: Auto-Dismiss Alerts
// ------------------------------
function renderAlert($type, $msg) {
    if (!$msg) return '';
    $typeClass = ($type === 'success') ? 'alert-success' : (($type === 'warning') ? 'alert-warning' : 'alert-danger');
    return '
    <div class="alert '.$typeClass.' alert-dismissible fade show" role="alert">
        '.$msg.'
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <script>
      setTimeout(function() {
        var el = document.querySelector(".alert");
        if (el) { el.classList.remove("show"); el.classList.add("hide"); }
      }, 5000);
    </script>';
}

// ------------------------------
// Eingaben
// ------------------------------
$q        = trim($_GET['q'] ?? '');
$type     = trim($_GET['type'] ?? '');
$reason   = trim($_GET['reason'] ?? '');
$status   = trim($_GET['status'] ?? 'active'); // active|inactive|all
$page     = max(1, (int)($_GET['page'] ?? 1));
$perPage  = 25;
$offset   = ($page - 1) * $perPage;

// Flash messages via GET
$success = $_GET['success'] ?? '';
$error   = $_GET['error'] ?? '';

// ------------------------------
// CSV Import (POST)
// ------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_csv'])) {
    $importType   = $_POST['import_type'] ?? 'email';
    $importReason = $_POST['import_reason'] ?? 'manual';
    $importListId = isset($_POST['import_list_id']) && $_POST['import_list_id'] !== '' ? (int)$_POST['import_list_id'] : null;

    try {
        if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('CSV-Datei fehlt oder Upload-Fehler.');
        }

        $tmpPath = $_FILES['csv_file']['tmp_name'];
        $content = file_get_contents($tmpPath);
        if ($content === false || trim($content) === '') {
            throw new Exception('CSV-Datei ist leer.');
        }

        // CSV: eine E-Mail/Domain pro Zeile, optional mit Semikolon getrennten Spalten
        // Beispiel:
        // email@example.com
        // example.com
        // email@example.com;hardbounce;Kommentar
        $lines = preg_split("/\r\n|\n|\r/", $content);
        $lines = array_filter(array_map('trim', $lines));

        $inserted = 0;
        $skipped  = 0;

        $db->beginTransaction();

        $sqlInsert = "INSERT INTO suppression_list (list_id, type, value, reason, details, is_active, created_by_user_id)
                      VALUES (:list_id, :type, :value, :reason, :details, 1, :created_by)";
        $stmtInsert = $db->prepare($sqlInsert);

        foreach ($lines as $line) {
            if ($line === '') continue;

            $parts = array_map('trim', explode(';', $line));
            $value = $parts[0] ?? '';
            $r     = $parts[1] ?? $importReason;
            $d     = $parts[2] ?? null;

            if ($value === '') { $skipped++; continue; }

            // Normalisierung
            $valueNorm = strtolower($value);
            if ($importType === 'domain') {
                $valueNorm = preg_replace('/^@/', '', $valueNorm);
            }

            // Duplikate vermeiden: wenn gleicher active Eintrag existiert -> skip
            $sqlCheck = "SELECT id FROM suppression_list WHERE type = ? AND value = ? AND is_active = 1 AND ((list_id IS NULL AND ? IS NULL) OR (list_id = ?)) LIMIT 1";
            $stmtCheck = $db->prepare($sqlCheck);
            $stmtCheck->execute([$importType, $valueNorm, $importListId, $importListId]);
            if ($stmtCheck->fetchColumn()) {
                $skipped++;
                continue;
            }

            $stmtInsert->execute([
                ':list_id'    => $importListId,
                ':type'       => $importType,
                ':value'      => $valueNorm,
                ':reason'     => in_array($r, ['manual','unsubscribe','hardbounce','complaint','other'], true) ? $r : 'other',
                ':details'    => $d,
                ':created_by' => $_SESSION['user_id'] ?? null
            ]);

            $inserted++;
        }

        $db->commit();
        ErrorLogger::logSqlSuccess('CSV Import Sperrliste | context: ' . json_encode(['inserted' => $inserted, 'skipped' => $skipped], JSON_UNESCAPED_UNICODE));

        header('Location: sperrliste.php?success=imported&ins='.$inserted.'&skip='.$skipped);
        exit;
    } catch (Exception $e) {
        if ($db->inTransaction()) $db->rollBack();
        ErrorLogger::logSqlError('CSV Import Sperrliste fehlgeschlagen | error: ' . $e->getMessage());
        header('Location: sperrliste.php?error=import_failed');
        exit;
    }
}

// ------------------------------
// Query bauen
// ------------------------------
$where = [];
$params = [];

if ($q !== '') {
    $where[] = "value LIKE ?";
    $params[] = '%' . $q . '%';
}
if ($type !== '' && in_array($type, ['email','domain'], true)) {
    $where[] = "type = ?";
    $params[] = $type;
}
if ($reason !== '' && in_array($reason, ['manual','unsubscribe','hardbounce','complaint','other'], true)) {
    $where[] = "reason = ?";
    $params[] = $reason;
}
if ($status === 'active') {
    $where[] = "is_active = 1";
} elseif ($status === 'inactive') {
    $where[] = "is_active = 0";
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

// ------------------------------
// Daten laden
// ------------------------------
$rows = [];
$total = 0;

try {
    // Count
    $stmtCount = $db->prepare("SELECT COUNT(*) FROM suppression_list $whereSql");
    $stmtCount->execute($params);
    $total = (int)$stmtCount->fetchColumn();

    // Data
    $stmt = $db->prepare("SELECT * FROM suppression_list $whereSql ORDER BY created_at DESC LIMIT $perPage OFFSET $offset");
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    ErrorLogger::logSqlSuccess('Sperrliste Laden | context: ' . json_encode(['total' => $total, 'page' => $page], JSON_UNESCAPED_UNICODE));
} catch (Exception $e) {
    ErrorLogger::logSqlError('Sperrliste Laden fehlgeschlagen | error: ' . $e->getMessage());
    $error = 'load_failed';
}

// Pagination
$totalPages = (int)ceil($total / $perPage);
$queryBase = http_build_query(array_filter([
    'q' => $q, 'type' => $type, 'reason' => $reason, 'status' => $status
]));

// ------------------------------
// UI Messages
// ------------------------------
$msg = '';
if ($success === 'imported') {
    $ins = (int)($_GET['ins'] ?? 0);
    $skip = (int)($_GET['skip'] ?? 0);
    $msg = renderAlert('success', '✅ CSV-Import abgeschlossen. Eingefügt: <strong>'.$ins.'</strong>, übersprungen: <strong>'.$skip.'</strong>.');
} elseif ($success === 'created') {
    $msg = renderAlert('success', '✅ Sperrlisten-Eintrag wurde angelegt.');
} elseif ($success === 'toggled') {
    $msg = renderAlert('success', '✅ Sperrlisten-Eintrag wurde aktualisiert.');
} elseif ($error === 'import_failed') {
    $msg = renderAlert('danger', '❌ CSV-Import fehlgeschlagen. Bitte Datei prüfen.');
} elseif ($error === 'load_failed') {
    $msg = renderAlert('danger', '❌ Sperrliste konnte nicht geladen werden.');
}

ob_start();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h3 mb-0">🛑 Sperrliste (Blacklist)</h1>
  <div>
    <a href="sperrliste_neu.php" class="btn btn-primary">➕ Eintrag anlegen</a>
  </div>
</div>

<?= $msg ?>

<div class="card mb-3">
  <div class="card-body">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-md-4">
        <label class="form-label">Suche (E-Mail / Domain)</label>
        <input type="text" name="q" class="form-control" value="<?= htmlspecialchars($q) ?>" placeholder="z.B. max@domain.de oder domain.de">
      </div>

      <div class="col-md-2">
        <label class="form-label">Typ</label>
        <select name="type" class="form-select">
          <option value="">Alle</option>
          <option value="email" <?= $type==='email'?'selected':'' ?>>E-Mail</option>
          <option value="domain" <?= $type==='domain'?'selected':'' ?>>Domain</option>
        </select>
      </div>

      <div class="col-md-2">
        <label class="form-label">Grund</label>
        <select name="reason" class="form-select">
          <option value="">Alle</option>
          <?php foreach (['manual'=>'Manuell','unsubscribe'=>'Abmeldung','hardbounce'=>'Hardbounce','complaint'=>'Beschwerde','other'=>'Sonstiges'] as $k=>$v): ?>
            <option value="<?= $k ?>" <?= $reason===$k?'selected':'' ?>><?= $v ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-md-2">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <option value="active" <?= $status==='active'?'selected':'' ?>>Aktiv</option>
          <option value="inactive" <?= $status==='inactive'?'selected':'' ?>>Inaktiv</option>
          <option value="all" <?= $status==='all'?'selected':'' ?>>Alle</option>
        </select>
      </div>

      <div class="col-md-2 d-grid">
        <button class="btn btn-secondary" type="submit">🔍 Filtern</button>
      </div>
    </form>
  </div>
</div>

<div class="card mb-4">
  <div class="card-header d-flex justify-content-between align-items-center">
    <strong>📄 Liste</strong>
    <span class="text-muted">Einträge: <?= (int)$total ?></span>
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped mb-0 align-middle">
        <thead>
          <tr>
            <th>ID</th>
            <th>Typ</th>
            <th>Wert</th>
            <th>Grund</th>
            <th>Status</th>
            <th>Gültig bis</th>
            <th>Erstellt</th>
            <th class="text-end">Aktion</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="8" class="text-center py-4 text-muted">Keine Einträge gefunden.</td></tr>
          <?php else: ?>
            <?php foreach ($rows as $r): ?>
              <tr>
                <td><?= (int)$r['id'] ?></td>
                <td><?= htmlspecialchars($r['type']) ?></td>
                <td><code><?= htmlspecialchars($r['value']) ?></code></td>
                <td><?= htmlspecialchars($r['reason']) ?></td>
                <td>
                  <?php if ((int)$r['is_active'] === 1): ?>
                    <span class="badge bg-success">aktiv</span>
                  <?php else: ?>
                    <span class="badge bg-secondary">inaktiv</span>
                  <?php endif; ?>
                </td>
                <td><?= $r['expires_at'] ? htmlspecialchars($r['expires_at']) : '<span class="text-muted">–</span>' ?></td>
                <td><?= htmlspecialchars($r['created_at']) ?></td>
                <td class="text-end">
                  <?php if ((int)$r['is_active'] === 1): ?>
                    <a class="btn btn-sm btn-outline-danger"
                       href="sperrliste_delete.php?id=<?= (int)$r['id'] ?>&action=deactivate"
                       onclick="return confirm('Eintrag wirklich deaktivieren?');">⛔ Deaktivieren</a>
                  <?php else: ?>
                    <a class="btn btn-sm btn-outline-success"
                       href="sperrliste_delete.php?id=<?= (int)$r['id'] ?>&action=activate"
                       onclick="return confirm('Eintrag wieder aktivieren?');">✅ Aktivieren</a>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <?php if ($totalPages > 1): ?>
    <div class="card-footer d-flex justify-content-between align-items-center">
      <div class="text-muted">Seite <?= $page ?> / <?= $totalPages ?></div>
      <nav>
        <ul class="pagination mb-0">
          <?php for ($p=1; $p<=$totalPages; $p++): ?>
            <li class="page-item <?= $p===$page?'active':'' ?>">
              <a class="page-link" href="sperrliste.php?<?= $queryBase ?>&page=<?= $p ?>"><?= $p ?></a>
            </li>
          <?php endfor; ?>
        </ul>
      </nav>
    </div>
  <?php endif; ?>
</div>

<div class="card">
  <div class="card-header"><strong>⬆️ CSV-Import</strong></div>
  <div class="card-body">
    <p class="text-muted mb-2">
      Format: Eine E-Mail/Domain pro Zeile. Optional: <code>wert;grund;details</code> (z. B. <code>max@domain.de;hardbounce;Mailbox unknown</code>)
    </p>

    <form method="post" enctype="multipart/form-data" class="row g-2 align-items-end">
      <input type="hidden" name="import_csv" value="1">

      <div class="col-md-3">
        <label class="form-label">Typ</label>
        <select name="import_type" class="form-select">
          <option value="email">E-Mail</option>
          <option value="domain">Domain</option>
        </select>
      </div>

      <div class="col-md-3">
        <label class="form-label">Standard-Grund</label>
        <select name="import_reason" class="form-select">
          <?php foreach (['manual'=>'Manuell','unsubscribe'=>'Abmeldung','hardbounce'=>'Hardbounce','complaint'=>'Beschwerde','other'=>'Sonstiges'] as $k=>$v): ?>
            <option value="<?= $k ?>"><?= $v ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-md-3">
        <label class="form-label">Listen-ID (optional)</label>
        <input type="number" name="import_list_id" class="form-control" placeholder="leer = global">
      </div>

      <div class="col-md-3">
        <label class="form-label">CSV-Datei</label>
        <input type="file" name="csv_file" class="form-control" accept=".csv,.txt" required>
      </div>

      <div class="col-12 d-grid mt-2">
        <button class="btn btn-primary" type="submit">📥 Import starten</button>
      </div>
    </form>
  </div>
</div>

<?php
$pageContent = ob_get_clean();
include_once __DIR__ . '/../template.php';
