<?php
// admin/empfaenger/sperrliste_neu.php
// Neuen Sperrlisten-Eintrag anlegen

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 – Eintrag anlegen';

$errorMsg = '';
$successMsg = '';

$type = $_POST['type'] ?? 'email';
$value = trim($_POST['value'] ?? '');
$reason = $_POST['reason'] ?? 'manual';
$details = trim($_POST['details'] ?? '');
$list_id = ($_POST['list_id'] ?? '') !== '' ? (int)$_POST['list_id'] : null;
$expires_at = trim($_POST['expires_at'] ?? ''); // optional datetime-local

// Alert helper
function alertBox($type, $msg) {
    if (!$msg) return '';
    $typeClass = ($type === 'success') ? 'alert-success' : '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>';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Validierung
        if (!in_array($type, ['email','domain'], true)) {
            throw new Exception('Ungültiger Typ.');
        }
        if ($value === '') {
            throw new Exception('Bitte einen Wert (E-Mail oder Domain) eingeben.');
        }
        if (!in_array($reason, ['manual','unsubscribe','hardbounce','complaint','other'], true)) {
            $reason = 'other';
        }

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

        // expires_at optional
        $expiresAtDb = null;
        if ($expires_at !== '') {
            // HTML datetime-local kommt z.B. 2026-02-02T14:30
            $expiresAtDb = str_replace('T', ' ', $expires_at) . ':00';
        }

        // Duplikate verhindern (aktiv)
        $stmtCheck = $db->prepare("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->execute([$type, $valueNorm, $list_id, $list_id]);
        if ($stmtCheck->fetchColumn()) {
            throw new Exception('Dieser Eintrag ist bereits aktiv vorhanden.');
        }

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

        $stmt->execute([
            ':list_id'    => $list_id,
            ':type'       => $type,
            ':value'      => $valueNorm,
            ':reason'     => $reason,
            ':details'    => $details !== '' ? $details : null,
            ':expires_at' => $expiresAtDb,
            ':created_by' => $_SESSION['user_id'] ?? null
        ]);

        ErrorLogger::logSqlSuccess('Sperrlisten-Eintrag angelegt | context: ' . json_encode(['type' => $type, 'value' => $valueNorm], JSON_UNESCAPED_UNICODE));

        header('Location: sperrliste.php?success=created');
        exit;

    } catch (Exception $e) {
        ErrorLogger::logSqlError('Sperrlisten-Eintrag anlegen fehlgeschlagen | error: ' . $e->getMessage());
        $errorMsg = $e->getMessage();
    }
}

$fieldTooltips = [
    '[name="type"]' => 'Legt fest, ob eine einzelne E-Mail-Adresse oder eine ganze Domain gesperrt wird.',
    '[name="value"]' => 'Zu sperrender Wert, je nach Typ als E-Mail-Adresse oder Domain.',
    '[name="list_id"]' => 'Optional auf eine bestimmte Liste begrenzen. Leer bedeutet global.',
    '[name="reason"]' => 'Fachlicher Grund für die Sperrung.',
    '[name="expires_at"]' => 'Optionales Ablaufdatum, ab dem die Sperre automatisch endet.',
    '[name="details"]' => 'Zusätzliche interne Hinweise, etwa Ticket-ID oder Bounce-Text.',
];

ob_start();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h3 mb-0">➕ Sperrliste – Eintrag anlegen</h1>
  <a href="sperrliste.php" class="btn btn-secondary">↩ Zur Übersicht</a>
</div>

<?= alertBox('danger', $errorMsg) ?>

<div class="card">
  <div class="card-body">
    <form method="post" class="row g-3">
      <div class="col-md-3">
        <label class="form-label">Typ</label>
        <select name="type" class="form-select">
          <option value="email" <?= $type==='email'?'selected':'' ?>>E-Mail</option>
          <option value="domain" <?= $type==='domain'?'selected':'' ?>>Domain</option>
        </select>
      </div>

      <div class="col-md-6">
        <label class="form-label">Wert</label>
        <input type="text" name="value" class="form-control" value="<?= htmlspecialchars($value) ?>" placeholder="max@domain.de oder domain.de" required>
        <div class="form-text">Bei Domain: ohne @ eingeben (z. B. <code>example.com</code>).</div>
      </div>

      <div class="col-md-3">
        <label class="form-label">Listen-ID (optional)</label>
        <input type="number" name="list_id" class="form-control" value="<?= htmlspecialchars($_POST['list_id'] ?? '') ?>" placeholder="leer = global">
      </div>

      <div class="col-md-4">
        <label class="form-label">Grund</label>
        <select name="reason" class="form-select">
          <?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-4">
        <label class="form-label">Gültig bis (optional)</label>
        <input type="datetime-local" name="expires_at" class="form-control" value="<?= htmlspecialchars($expires_at) ?>">
      </div>

      <div class="col-12">
        <label class="form-label">Details (optional)</label>
        <textarea name="details" class="form-control" rows="3" placeholder="z.B. Bounce-Text, Ticket-ID, Hinweis..."><?= htmlspecialchars($details) ?></textarea>
      </div>

      <div class="col-12 d-grid">
        <button class="btn btn-primary" type="submit">✅ Eintrag speichern</button>
      </div>
    </form>
  </div>
</div>

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