<?php
// admin/campaigns/trigger_transaction.php

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 = 'Transaktionsmail auslösen';
$message = '';
$error = '';
$campaigns = [];

$sqlCampaigns = "SELECT id, name FROM campaigns WHERE type = 'transaction' ORDER BY name ASC";
try {
    $campaigns = $db->query($sqlCampaigns)->fetchAll();
    ErrorLogger::logSqlSuccess('trigger_transaction: load campaigns | SQL: ' . $sqlCampaigns . ' | params: []');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('trigger_transaction: load campaigns failed | SQL: ' . $sqlCampaigns . ' | params: [] | error: ' . $e->getMessage());
    $campaigns = [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $recipientId = (int)($_POST['recipient_id'] ?? 0);
    $campaignId = (int)($_POST['campaign_id'] ?? 0);

    if (!$recipientId || !$campaignId) {
        $error = 'Bitte Empfänger-ID und Kampagne angeben.';
    } else {
        try {
            $sqlCampaign = "SELECT * FROM campaigns WHERE id = ? AND type = 'transaction' LIMIT 1";
            $stmt = $db->prepare($sqlCampaign);
            $stmt->execute([$campaignId]);
            $campaign = $stmt->fetch();
            ErrorLogger::logSqlSuccess('trigger_transaction: load selected campaign | SQL: ' . $sqlCampaign . ' | params: ' . json_encode([$campaignId], JSON_UNESCAPED_UNICODE));

            if (!$campaign) {
                $error = 'Kampagne nicht gefunden oder kein Transaktionstyp.';
            } else {
                $sqlRecipient = 'SELECT COUNT(*) FROM recipients WHERE id = ?';
                $exists = $db->prepare($sqlRecipient);
                $exists->execute([$recipientId]);
                ErrorLogger::logSqlSuccess('trigger_transaction: check recipient exists | SQL: ' . $sqlRecipient . ' | params: ' . json_encode([$recipientId], JSON_UNESCAPED_UNICODE));

                if ($exists->fetchColumn() == 0) {
                    $error = 'Empfänger nicht gefunden.';
                } else {
                    $sqlCheckQueue = 'SELECT COUNT(*) FROM send_queue WHERE campaign_id = ? AND recipient_id = ?';
                    $check = $db->prepare($sqlCheckQueue);
                    $check->execute([$campaignId, $recipientId]);
                    ErrorLogger::logSqlSuccess('trigger_transaction: check queue duplicate | SQL: ' . $sqlCheckQueue . ' | params: ' . json_encode([$campaignId, $recipientId], JSON_UNESCAPED_UNICODE));

                    if ($check->fetchColumn() > 0) {
                        $message = 'Diese Kombination ist bereits eingeplant.';
                    } else {
                        $viewToken = bin2hex(random_bytes(16));
                        $priority = $campaign['priority'] ?? 3;

                        $sqlInsertQueue = "INSERT INTO send_queue (campaign_id, recipient_id, template_id, view_token, scheduled_at, status, created_at, priority) VALUES (?, ?, ?, ?, NOW(), 'pending', NOW(), ?)";
                        $insert = $db->prepare($sqlInsertQueue);
                        $insert->execute([
                            $campaignId,
                            $recipientId,
                            $campaign['template_id'],
                            $viewToken,
                            $priority
                        ]);
                        ErrorLogger::logSqlSuccess('trigger_transaction: insert queue | SQL: ' . $sqlInsertQueue . ' | params: ' . json_encode([$campaignId, $recipientId, $campaign['template_id'], $viewToken, $priority], JSON_UNESCAPED_UNICODE));

                        $message = 'Transaktionsmail wurde eingeplant.';
                        ErrorLogger::log('Transaktionsmail geplant: Kampagne #' . $campaignId . ' an Empfänger #' . $recipientId, 'INFO');
                    }
                }
            }
        } catch (Throwable $e) {
            ErrorLogger::logSqlError('trigger_transaction: workflow failed | params: ' . json_encode([$campaignId, $recipientId], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
            $error = 'Interner Fehler beim Ausloesen der Transaktionsmail.';
        }
    }
}

$fieldTooltips = [
    '[name="campaign_id"]' => 'Transaktionskampagne, die für diesen Einzelvorgang eingeplant werden soll.',
    '[name="recipient_id"]' => 'Interne Empfänger-ID, an die die Transaktionsmail geschickt werden soll.',
];

ob_start();
?>
<div class="page-header h2">Transaktionsmail auslösen</div>

<?php if ($message): ?>
  <div class="alert alert-success auto-dismiss"><?= htmlspecialchars($message) ?></div>
<?php elseif ($error): ?>
  <div class="alert alert-danger auto-dismiss"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<form method="post">
  <div class="mb-3">
    <label for="campaign_id" class="form-label">Transaktions-Kampagne</label>
    <select name="campaign_id" id="campaign_id" class="form-select" required>
      <option value="">-- Bitte wählen --</option>
      <?php foreach ($campaigns as $c): ?>
        <option value="<?= $c['id'] ?>" <?= isset($_POST['campaign_id']) && $_POST['campaign_id'] == $c['id'] ? 'selected' : '' ?>>
          <?= htmlspecialchars($c['name']) ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="mb-3">
    <label for="recipient_id" class="form-label">Empfänger-ID</label>
    <input type="number" name="recipient_id" id="recipient_id" class="form-control" required value="<?= htmlspecialchars($_POST['recipient_id'] ?? '') ?>">
  </div>

  <button type="submit" class="btn btn-primary">Transaktion auslösen</button>
  <a href="campaigns.php" class="btn btn-secondary">Zurück</a>
</form>

<script>
setTimeout(() => {
  document.querySelectorAll('.auto-dismiss').forEach(el => el.remove());
}, 5000);
</script>

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