<?php
/**
 * admin/campaigns/campaign_delete.php
 * ----------------------------------------------------------------------
 * 🗑️ Kampagne löschen (Admin)
 * ----------------------------------------------------------------------
 * • Sicherheitsabfrage vor dem Löschen
 * • SQL-Logging bei Erfolg/Fehler über ErrorLogger::logSqlSuccess/logSqlError
 * • Fehlerbehandlung via try/catch
 * • Auto-Dismiss Hinweise (UX)
 * ----------------------------------------------------------------------
 */

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

/* =========================================================================
 * Auth prüfen
 * ========================================================================= */
$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: ' . $adminLoginPath);
    exit;
}

/* =========================================================================
 * DB + Grundwerte
 * ========================================================================= */
$db    = Database::getInstance();
$title = 'Kampagne löschen';
$error = '';

/* =========================================================================
 * Kampagne-ID prüfen
 * ========================================================================= */
$campaignId = $_GET['id'] ?? null;
if (!$campaignId || !is_numeric($campaignId)) {
    header('Location: campaigns.php');
    exit;
}
$campaignId = (int)$campaignId;

/* =========================================================================
 * Kampagne laden (für Bestätigung)
 * ========================================================================= */
$campaign = null;
$sqlSelect = "SELECT id, name FROM campaigns WHERE id = ? LIMIT 1";
$paramsSelect = [$campaignId];

try {
    $stmt = $db->prepare($sqlSelect);
    $stmt->execute($paramsSelect);
    $campaign = $stmt->fetch(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('campaign_delete: select campaign | SQL: ' . $sqlSelect . ' | params: ' . json_encode($paramsSelect, JSON_UNESCAPED_UNICODE));
} catch (Throwable $e) {
    ErrorLogger::logSqlError('campaign_delete: select campaign failed | SQL: ' . $sqlSelect . ' | params: ' . json_encode($paramsSelect, JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    $error = 'Kampagne konnte nicht geladen werden.';
}

/* =========================================================================
 * Löschen (nach Bestätigung)
 * ========================================================================= */
if ($campaign && $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['confirm'] ?? '') === 'yes') {
    $sqlDelete = "DELETE FROM campaigns WHERE id = ? LIMIT 1";
    $paramsDelete = [$campaignId];

    try {
        $stmt = $db->prepare($sqlDelete);
        $stmt->execute($paramsDelete);
        ErrorLogger::logSqlSuccess('campaign_delete: delete campaign | SQL: ' . $sqlDelete . ' | params: ' . json_encode($paramsDelete, JSON_UNESCAPED_UNICODE));

        header('Location: campaigns.php?deleted=1');
        exit;
    } catch (Throwable $e) {
        ErrorLogger::logSqlError('campaign_delete: delete campaign failed | SQL: ' . $sqlDelete . ' | params: ' . json_encode($paramsDelete, JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
        $error = 'Fehler beim Löschen: ' . $e->getMessage();
    }
}

/* =========================================================================
 * VIEW via Template
 * ========================================================================= */
ob_start();
?>
<div class="page-header h2">🗑️ Kampagne löschen</div>

<?php if (!empty($error)): ?>
  <div class="alert alert-danger alert-dismissible fade show" role="alert" data-autodismiss="9000">
    ❌ <?= htmlspecialchars($error) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Schließen"></button>
  </div>
<?php endif; ?>

<?php if (empty($error) && !$campaign): ?>
  <div class="alert alert-warning alert-dismissible fade show" role="alert" data-autodismiss="9000">
    ⚠️ Kampagne nicht gefunden.
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Schließen"></button>
  </div>
  <a href="campaigns.php" class="btn btn-secondary">Zurück</a>
<?php endif; ?>

<?php if ($campaign): ?>
  <div class="alert alert-warning alert-dismissible fade show" role="alert">
    <strong>Achtung:</strong> Möchtest du die Kampagne <strong><?= htmlspecialchars($campaign['name']) ?></strong> wirklich dauerhaft löschen?
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Schließen"></button>
  </div>

  <form method="post" class="mt-3">
    <input type="hidden" name="confirm" value="yes">
    <button type="submit" class="btn btn-danger">🚨 Ja, Kampagne löschen</button>
    <a href="campaigns.php" class="btn btn-secondary">Abbrechen</a>
  </form>
<?php endif; ?>

<script>
/**
 * Auto-Dismiss für Alerts (progressive enhancement).
 * Voraussetzung: Bootstrap JS im Template.
 */
(function () {
  try {
    document.querySelectorAll('.alert[data-autodismiss]').forEach(function (el) {
      var ms = parseInt(el.getAttribute('data-autodismiss'), 10);
      if (!ms || ms < 1000) return;
      window.setTimeout(function () {
        if (window.bootstrap && bootstrap.Alert) {
          bootstrap.Alert.getOrCreateInstance(el).close();
        } else {
          el.remove();
        }
      }, ms);
    });
  } catch (e) {}
})();
</script>

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

