<?php
/**
 * admin/emails/campaigns.php
 * ----------------------------------------------------------------------
 * 📣 Kampagnen verwalten (Übersicht)
 * ----------------------------------------------------------------------
 * Anpassung für neue Segmentierung (MR9):
 *  • campaigns.list_id (optional)
 *  • campaigns.tag_id (optional)
 *  • campaigns.tag_mode (include|exclude|null)
 *
 * Legacy-Fallback:
 *  • filter_type / filter_value bleiben für Alt-Kampagnen nutzbar
 *
 * Logging:
 *  • Alle SQL-Operationen try/catch
 *  • ErrorLogger::logSqlSuccess / ErrorLogger::logSqlError
 * ----------------------------------------------------------------------
 */

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 = 'E-Mail-Kampagnen';

/* =========================================================================
 * Kampagne aktivieren (Status -> scheduled)
 * ========================================================================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['activate_campaign_id'])) {
    $campaignId = (int)($_POST['activate_campaign_id'] ?? 0);

    if ($campaignId > 0) {
        $sql = "UPDATE campaigns SET status = 'scheduled' WHERE id = ?";
        $params = [$campaignId];

        try {
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            ErrorLogger::logSqlSuccess('campaigns: activate | SQL: ' . $sql . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE));

            header('Location: campaigns.php?success=activated');
            exit;
        } catch (Throwable $e) {
            ErrorLogger::logSqlError('campaigns: activate failed | SQL: ' . $sql . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());

            header('Location: campaigns.php?error=activate_failed');
            exit;
        }
    }
}

/* =========================================================================
 * Filter (GET)
 * ========================================================================= */
$typeFilter = $_GET['type'] ?? '';
$listFilter = $_GET['list'] ?? '';

$where  = [];
$params = [];

if (!empty($typeFilter)) {
    $where[]  = "c.type = ?";
    $params[] = $typeFilter;
}

/**
 * Listen-Filter:
 * - bevorzugt neues Feld campaigns.list_id
 * - fallback: Alt-Kampagnen über filter_type/value
 */
if (!empty($listFilter)) {
    $where[]  = "(c.list_id = ? OR (c.list_id IS NULL AND c.filter_type = 'list' AND c.filter_value = ?))";
    $params[] = $listFilter;
    $params[] = $listFilter;
}

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

/* =========================================================================
 * Listen für Dropdown
 * ========================================================================= */
$lists = [];
try {
    $sql = "SELECT id, name FROM lists ORDER BY name ASC";
    $lists = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('campaigns: load list dropdown | SQL: ' . $sql . ' | params: []');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('campaigns: load list dropdown failed | SQL: ' . ($sql ?? 'SELECT lists') . ' | params: [] | error: ' . $e->getMessage());
    $lists = [];
}

/* =========================================================================
 * Kampagnen laden
 *  - Join auf neue Felder (list_id, tag_id)
 *  - Legacy-Fallback (filter_type/value)
 * ========================================================================= */
$campaignRows = [];

$sqlCampaigns = <<<SQL
SELECT
    c.*,

    /* Template */
    t.id   AS template_id,
    t.name AS template_name,

    /* Neue Segment-Felder */
    l.name  AS list_name,
    tg.name AS tag_name,

    /* Legacy-Fallback */
    l2.name  AS legacy_list_name,
    tg2.name AS legacy_tag_name

FROM campaigns c
LEFT JOIN email_templates t ON c.template_id = t.id

/* Neue Felder */
LEFT JOIN lists l  ON l.id  = c.list_id
LEFT JOIN tags  tg ON tg.id = c.tag_id

/* Legacy: Listenkampagne */
LEFT JOIN lists l2
       ON (c.list_id IS NULL
           AND c.filter_type = 'list'
           AND l2.id = c.filter_value)

/* Legacy: Tagkampagne (Altformat: "tag:ID") */
LEFT JOIN tags tg2
       ON (c.tag_id IS NULL
           AND c.filter_type = 'tag'
           AND tg2.id = REPLACE(c.filter_value,'tag:',''))

$whereSql
ORDER BY c.created_at DESC
SQL;

try {
    $stmt = $db->prepare($sqlCampaigns);
    $stmt->execute($params);
    ErrorLogger::logSqlSuccess('campaigns: load campaigns | SQL: ' . $sqlCampaigns . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE));

    $campaignRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    ErrorLogger::logSqlError('campaigns: load campaigns failed | SQL: ' . $sqlCampaigns . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    $campaignRows = [];
}

/* =========================================================================
 * Zielgruppen-Text (Klartext)
 *  - Wenn list_id gesetzt => Liste: X
 *  - Wenn tag_id gesetzt  => Tag: Y / Tag: NICHT Y
 *  - Tag ohne Liste wirkt global (Hinweis in Text)
 * ========================================================================= */
foreach ($campaignRows as &$c) {
    $listName = $c['list_name'] ?? $c['legacy_list_name'] ?? null;
    $tagName  = $c['tag_name']  ?? $c['legacy_tag_name']  ?? null;

    $parts = [];

    if (!empty($listName)) {
        $parts[] = 'Liste: ' . $listName;
    }

    if (!empty($tagName)) {
        $mode = $c['tag_mode'] ?? null;
        $parts[] = ($mode === 'exclude') ? ('Tag: NICHT ' . $tagName) : ('Tag: ' . $tagName);

        // Wenn Tag gesetzt, aber keine Liste -> globaler Hinweis
        if (empty($listName)) {
            $parts[] = '(global)';
        }
    }

    $c['zielgruppe_text'] = empty($parts) ? 'Alle Empfänger' : implode(' · ', $parts);
}
unset($c);

/* =========================================================================
 * VIEW
 * ========================================================================= */
ob_start();
?>
<div class="page-header h2">📣 Kampagnen verwalten</div>

<?php if (($_GET['success'] ?? '') === 'activated'): ?>
  <div class="alert alert-success alert-dismissible fade show" role="alert" data-autodismiss="7000">
    ✅ Kampagne wurde aktiviert (Status: scheduled).
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Schließen"></button>
  </div>
<?php endif; ?>

<?php if (($_GET['error'] ?? '') === 'activate_failed'): ?>
  <div class="alert alert-danger alert-dismissible fade show" role="alert" data-autodismiss="9000">
    ❌ Aktivierung fehlgeschlagen. Bitte Logs prüfen.
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Schließen"></button>
  </div>
<?php endif; ?>

<p>
  <a href="campaign_create.php" class="btn btn-primary mb-3">+ Neue Kampagne</a>
</p>

<form method="get" class="mb-3 d-flex gap-3">
  <div>
    <label for="type" class="form-label">Typ</label>
    <select name="type" id="type" class="form-select">
      <option value="">-- Alle --</option>
      <option value="date" <?= $typeFilter === 'date' ? 'selected' : '' ?>>📅 Nach Datum</option>
      <option value="followup" <?= $typeFilter === 'followup' ? 'selected' : '' ?>>⏱️ Follow-Up</option>
      <option value="transaction" <?= $typeFilter === 'transaction' ? 'selected' : '' ?>>⚡ Transaktionsmail</option>
    </select>
  </div>

  <div>
    <label for="list" class="form-label">Liste</label>
    <select name="list" id="list" class="form-select">
      <option value="">-- Alle --</option>
      <?php foreach ($lists as $list): ?>
        <option value="<?= (int)$list['id'] ?>" <?= ((string)$listFilter === (string)$list['id']) ? 'selected' : '' ?>>
          <?= htmlspecialchars((string)$list['name']) ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="align-self-end">
    <button type="submit" class="btn btn-outline-secondary">Filtern</button>
    <a href="campaigns.php" class="btn btn-outline-light">Zurücksetzen</a>
  </div>
</form>

<div class="table-responsive">
<table class="table table-striped align-middle">
  <thead>
    <tr>
      <th>Name</th>
      <th>Vorlage</th>
      <th>Zielgruppe</th>
      <th>Status</th>
      <th>Geplant für</th>
      <th style="width:260px;">Aktionen</th>
    </tr>
  </thead>
  <tbody>
    <?php if (empty($campaignRows)): ?>
      <tr>
        <td colspan="6" class="text-muted">Keine Kampagnen gefunden.</td>
      </tr>
    <?php endif; ?>

    <?php foreach ($campaignRows as $campaign): ?>
    <tr>
      <td><?= htmlspecialchars((string)$campaign['name']) ?></td>

      <td>
        <?php if (!empty($campaign['template_name']) && !empty($campaign['template_id'])): ?>
          <a href="../emails/template_edit.php?id=<?= (int)$campaign['template_id'] ?>">📝 <?= htmlspecialchars((string)$campaign['template_name']) ?></a>
        <?php else: ?>
          <span class="text-muted">-</span>
        <?php endif; ?>
      </td>

      <td><?= htmlspecialchars((string)($campaign['zielgruppe_text'] ?? 'Alle Empfänger')) ?></td>

      <td><?= htmlspecialchars((string)$campaign['status']) ?></td>

      <td><?= !empty($campaign['schedule_at']) ? htmlspecialchars((string)$campaign['schedule_at']) : '<span class="text-muted">-</span>' ?></td>

      <td>
        <a href="campaign_edit.php?id=<?= (int)$campaign['id'] ?>" class="btn btn-sm btn-outline-primary">Bearbeiten</a>
        <a href="campaign_delete.php?id=<?= (int)$campaign['id'] ?>" class="btn btn-sm btn-outline-danger"
           onclick="return confirm('Diese Kampagne wirklich löschen?')">Löschen</a>

        <?php if (($campaign['status'] ?? '') === 'draft'): ?>
          <form method="post" style="display:inline;">
            <input type="hidden" name="activate_campaign_id" value="<?= (int)$campaign['id'] ?>">
            <button type="submit" class="btn btn-sm btn-success"
                    onclick="return confirm('Kampagne jetzt aktivieren?')">Aktivieren</button>
          </form>
        <?php endif; ?>
      </td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>
</div>

<script>
/**
 * Auto-Dismiss für Alerts (progressive enhancement).
 */
(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';


