<?php
/**
 * confirm.php
 * -------------------------------------------------------------
 * Bestätigungs‑Endpunkt für Double‑Opt‑In‑Links
 * -------------------------------------------------------------
 * ▸ Aktualisiert Opt‑In‑Datensatz mit IP (enc + Hash), Timestamp usw.
 * ▸ Plant optionale Welcome‑Mail ein
 * ▸ Zieht alle Kryptoschlüssel & Salts aus includes/config.php
 * ▸ Vollständiges ErrorLogger‑Auditing
 */



require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/core/SodiumCrypto.php';

// -----------------------------------------------------------
// 0. Konfiguration einlesen (DOI‑Key & HASH‑Salt)
// -----------------------------------------------------------
$config    = require __DIR__ . '/includes/config.php';
$hashSalt  = $config['security']['hash_salt'] ?? '';
$cryptoKey = $config['security']['doi_key']   ?? '';

// -----------------------------------------------------------
// 1. Grundeingaben validieren
// -----------------------------------------------------------
$token = $_GET['token'] ?? '';
if (!$token) {
    echo 'Ungültiger Bestätigungslink.';
    exit;
}

// -----------------------------------------------------------
// 2. DOI‑Datensatz laden
// -----------------------------------------------------------
$db   = Database::getInstance();
$stmt = $db->prepare('SELECT * FROM recipient_list_optin WHERE doi_token = ? AND doi_confirmed = 0 LIMIT 1');
$stmt->execute([$token]);
ErrorLogger::logSqlSuccess('confirm: load DOI token | SQL: ' . $stmt->queryString . ' | params: ' . json_encode([$token], JSON_UNESCAPED_UNICODE));

$optin = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$optin) {
    echo 'Token ungültig oder bereits bestätigt.';
    exit;
}

// -----------------------------------------------------------
// 3. Pseudonymisierte IP + Kontext fürs Klick‑Log
// -----------------------------------------------------------
$ipOriginal = $_SERVER['REMOTE_ADDR']     ?? 'unknown';
$ua         = $_SERVER['HTTP_USER_AGENT'] ?? null;
$referrer   = $_SERVER['HTTP_REFERER']    ?? null;

try {
    $ipCipher = SodiumCrypto::encrypt($ipOriginal, $cryptoKey);
    $ipHash   = hash_hmac('sha256', $ipOriginal, $hashSalt);
} catch (Throwable $e) {
    ErrorLogger::logSqlError('confirm: ip encryption failed | error: ' . $e->getMessage());
    $ipCipher = null;
    $ipHash   = hash_hmac('sha256', $ipOriginal, $hashSalt);
}

// -----------------------------------------------------------
// 4. Opt‑In‑Datensatz aktualisieren (Transaktion)
// -----------------------------------------------------------
try {
    $db->beginTransaction();

    $upd = $db->prepare(
        'UPDATE recipient_list_optin SET
            doi_confirmed       = 1,
            doi_confirmed_at    = NOW(),
            doi_ip_confirm_enc  = :ip_enc,
            doi_ip_confirm_hash = :ip_hash,
            doi_user_agent      = COALESCE(doi_user_agent, :ua),
            doi_referrer        = COALESCE(doi_referrer, :ref)
         WHERE doi_token = :token'
    );
    $upd->execute([
        ':ip_enc' => $ipCipher,
        ':ip_hash'=> $ipHash,
        ':ua'     => $ua,
        ':ref'    => $referrer,
        ':token'  => $token,
    ]);
    ErrorLogger::logSqlSuccess('confirm: update DOI record | SQL: ' . $upd->queryString . ' | params: ' . json_encode(['token' => $token], JSON_UNESCAPED_UNICODE));

    // -------------------------------------------------------
    // 4.1 Welcome‑Mail in Queue (falls definiert)
    // -------------------------------------------------------
    $recipientId = (int) $optin['recipient_id'];
    $listId      = (int) $optin['list_id'];
    $formId      = (int) $optin['formular_id'];

    $listStmt = $db->prepare('SELECT welcome_template_id FROM lists WHERE id = ?');
    $listStmt->execute([$listId]);
    ErrorLogger::logSqlSuccess('confirm: load welcome template | SQL: ' . $listStmt->queryString . ' | params: ' . json_encode([$listId], JSON_UNESCAPED_UNICODE));
    $list = $listStmt->fetch(PDO::FETCH_ASSOC) ?: [];

    if (!empty($list['welcome_template_id'])) {
        $queueStmt = $db->prepare(
            'INSERT INTO send_queue (campaign_id, recipient_id, template_id, view_token, priority, scheduled_at, status, created_at)
             VALUES (NULL, ?, ?, ?, 1, NOW(), "pending", NOW())'
        );
        $queueStmt->execute([
            $recipientId,
            $list['welcome_template_id'],
            bin2hex(random_bytes(16)),
        ]);
        ErrorLogger::logSqlSuccess('confirm: enqueue welcome mail | SQL: ' . $queueStmt->queryString . ' | params: ' . json_encode([$recipientId, $list['welcome_template_id']], JSON_UNESCAPED_UNICODE));
    }

    $db->commit();
} catch (Throwable $e) {
    $db->rollBack();
    ErrorLogger::logSqlError('confirm: transaction failed | error: ' . $e->getMessage());
    echo 'Ein Fehler ist aufgetreten. Bitte versuche es später erneut.';
    exit;
}

//------------------------------------------------------------
// 5. Direktversand (Prio 1) anstoßen
//------------------------------------------------------------
include __DIR__ . '/cron/send_queue_worker_s.php';


//------------------------------------------------------------
//------------------------------------------------------------
// 6. Redirect / Success-Message
//------------------------------------------------------------
try {
    $formStmt = $db->prepare(
        'SELECT redirect_url_confirm
           FROM forms
          WHERE id = :id
          LIMIT 1'
    );
    $formStmt->execute([':id' => (int) $formId]);
    $form = $formStmt->fetch(PDO::FETCH_ASSOC) ?: [];

    ErrorLogger::logSqlSuccess('confirm: redirect loaded | params: ' . json_encode(['form_id' => (int)$formId], JSON_UNESCAPED_UNICODE));

} catch (Throwable $e) {
    ErrorLogger::logSqlError('confirm: redirect load failed | error: ' . $e->getMessage());

}

if (!empty($form['redirect_url_confirm'])) {
    header('Location: ' . $form['redirect_url_confirm']);
    exit;
}

echo 'Vielen Dank für deine Bestätigung!';





