<?php
require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/config.php';

$config = include __DIR__ . '/includes/config.php';

$token = $_GET['token'] ?? '';

if ($token == 'test') {
    echo '<h1>Danke für ihren Test</h1>';
    exit;
}

if (!$token || strlen($token) < 10) {
    http_response_code(400);
    echo 'Ungültiger oder fehlender Token.';
    exit;
}

$db = Database::getInstance();

try {
    $sqlLoadMail = "SELECT q.id, q.template_id, q.recipient_id, t.subject, t.body_html, t.layout_id, l.editor_mode AS layout_editor_mode, l.source_content AS layout_source_content, l.header_html, l.footer_html
	                    FROM send_queue q
	                    JOIN email_templates t ON t.id = q.template_id
	                    LEFT JOIN email_layouts l ON l.id = t.layout_id
                    WHERE q.view_token = ?";
    $stmt = $db->prepare($sqlLoadMail);
    $stmt->execute([$token]);
    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('view: load mail by token | SQL: ' . $sqlLoadMail . ' | params: ' . json_encode([$token], JSON_UNESCAPED_UNICODE));

	    if (!$data) {
	        http_response_code(404);
	        echo 'Keine Nachricht gefunden.';
	        exit;
	    }

        if (!empty($data['layout_id'])) {
            $layoutState = mrPrepareLayoutEditorState([
                'editor_mode' => (string) ($data['layout_editor_mode'] ?? 'html'),
                'source_content' => (string) ($data['layout_source_content'] ?? ''),
                'header_html' => (string) ($data['header_html'] ?? ''),
                'footer_html' => (string) ($data['footer_html'] ?? ''),
            ]);
            $data['header_html'] = $layoutState['header_html'];
            $data['footer_html'] = $layoutState['footer_html'];
        }

	    $recipientId = (int)$data['recipient_id'];

    $sqlLoadRecipient = 'SELECT * FROM recipients WHERE id = ?';
    $stmt = $db->prepare($sqlLoadRecipient);
    $stmt->execute([$recipientId]);
    $recipient = $stmt->fetch(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('view: load recipient | SQL: ' . $sqlLoadRecipient . ' | params: ' . json_encode([$recipientId], JSON_UNESCAPED_UNICODE));

    if (!$recipient) {
        http_response_code(404);
        echo 'Empfänger nicht gefunden.';
        exit;
    }

    /**
     * Zusatzfelder laden.
     * Wir bauen danach bewusst eine normalisierte Map auf,
     * damit [field:Zusatzfeld] robuster ersetzt werden kann.
     */
    $sqlLoadFields = 'SELECT field_key, field_value FROM recipient_custom_fields WHERE recipient_id = ?';
    $stmt = $db->prepare($sqlLoadFields);
    $stmt->execute([$recipientId]);
    $customFieldsRaw = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('view: load custom fields | SQL: ' . $sqlLoadFields . ' | params: ' . json_encode([$recipientId], JSON_UNESCAPED_UNICODE));

} catch (Throwable $e) {
    ErrorLogger::logSqlError('view: initial load failed | params: ' . json_encode([$token], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    http_response_code(500);
    echo 'Interner Fehler. Bitte versuchen Sie es später erneut.';
    exit;
}

/**
 * -------------------------------------------------------------------------
 * Zusatzfelder normalisieren
 * -------------------------------------------------------------------------
 * Es wird eine robuste Zuordnung aufgebaut:
 *   Original-Key
 *   getrimmter Key
 *   lowercase-Key
 *
 * Dadurch werden Platzhalter in der Online-Ansicht toleranter ersetzt,
 * selbst wenn sich Groß-/Kleinschreibung oder Leerzeichen unterscheiden.
 */
$customFields = [];

foreach ($customFieldsRaw as $field) {
    $rawKey = (string)($field['field_key'] ?? '');
    $rawValue = (string)($field['field_value'] ?? '');

    $trimmedKey = trim($rawKey);
    $lowerKey   = mb_strtolower($trimmedKey, 'UTF-8');

    $customFields[$trimmedKey] = $rawValue;
    $customFields[$lowerKey]   = $rawValue;
}

/**
 * -------------------------------------------------------------------------
 * Zusatzfelder robust ersetzen
 * -------------------------------------------------------------------------
 * Ersetzt Platzhalter im Format:
 *   [field:Zusatzfeld]
 *   [field: zusatzfeld]
 *   [field:Zusatzfeld ]
 *
 * Falls kein passendes Feld gefunden wird, bleibt der Platzhalter erhalten.
 */
function ersetzeCustomFieldsWieImVersand(string $text, array $customFields): string
{
    return preg_replace_callback('/\[field:\s*([^\]]+?)\s*\]/u', function ($matches) use ($customFields) {
        $requestedKey = trim((string)$matches[1]);
        $requestedKeyLower = mb_strtolower($requestedKey, 'UTF-8');

        if (array_key_exists($requestedKey, $customFields)) {
            return (string)$customFields[$requestedKey];
        }

        if (array_key_exists($requestedKeyLower, $customFields)) {
            return (string)$customFields[$requestedKeyLower];
        }

        // Wenn kein Wert vorhanden ist:
        // Platzhalter NICHT stehen lassen, sondern leer ersetzen
        return '';
    }, $text);
}

/**
 * -------------------------------------------------------------------------
 * Standard-Platzhalter und System-Platzhalter ersetzen
 * -------------------------------------------------------------------------
 */
function ersetzePlatzhalter(string $text, array $daten, string $token = ''): string
{
    global $config;

    foreach ($daten as $key => $value) {
        $text = str_replace("[$key]", htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'), $text);
    }

    $systemPlatzhalter = [
        '[[datum]]'         => date('d.m.Y'),
        '[[jahr]]'          => date('Y'),
        '[unsubscribe_url]' => $config['app']['base_url'] . '/unsubscribe.php?token=' . $token,
        '[online_view_url]' => $config['app']['base_url'] . '/view.php?token=' . $token,
        '[pause_url]'       => $config['app']['base_url'] . '/versandpause.php?token=' . $token,
    ];

    foreach ($systemPlatzhalter as $key => $value) {
        $text = str_replace($key, $value, $text);
    }

    return $text;
}

/**
 * -------------------------------------------------------------------------
 * Links mit Tracking ersetzen
 * -------------------------------------------------------------------------
 */
function ersetzeLinksMitTracking(string $html, int $queueId, PDO $db, string $baseUrl): string
{
    return preg_replace_callback('/href=["\']([^"\']+)["\']/', function ($matches) use ($db, $queueId, $baseUrl) {
        $originalUrl = $matches[1];

        if (
            str_contains($originalUrl, '[') ||
            str_contains($originalUrl, 'unsubscribe.php') ||
            str_contains($originalUrl, 'confirm.php') ||
            str_contains($originalUrl, 'versandpause.php') ||
            str_contains($originalUrl, 'view.php')
        ) {
            return 'href="' . $originalUrl . '"';
        }

        try {
            $token = bin2hex(random_bytes(16));
            $sqlTrack = 'INSERT INTO email_link_tracking (token, original_url, queue_id) VALUES (?, ?, ?)';
            $stmt = $db->prepare($sqlTrack);
            $stmt->execute([$token, $originalUrl, $queueId]);
            ErrorLogger::logSqlSuccess('view: insert link tracking | SQL: ' . $sqlTrack . ' | params: ' . json_encode([$token, $originalUrl, $queueId], JSON_UNESCAPED_UNICODE));

            $trackedUrl = $baseUrl . '/click.php?token=' . $token;
            return 'href="' . $trackedUrl . '"';
        } catch (Throwable $e) {
            ErrorLogger::logSqlError('view: insert link tracking failed | params: ' . json_encode([$originalUrl, $queueId], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
            return 'href="' . $originalUrl . '"';
        }
    }, $html);
}

/* Rohinhalte laden */
$header  = $data['header_html'] ?? '';
$body    = $data['body_html'] ?? '';
$footer  = $data['footer_html'] ?? '';
$subject = $data['subject'] ?? '';

/* 1) Zusatzfelder robust ersetzen */
$header  = ersetzeCustomFieldsWieImVersand($header, $customFields);
$body    = ersetzeCustomFieldsWieImVersand($body, $customFields);
$footer  = ersetzeCustomFieldsWieImVersand($footer, $customFields);
$subject = ersetzeCustomFieldsWieImVersand($subject, $customFields);

/* 2) Normale Empfänger- und System-Platzhalter ersetzen */
$header  = ersetzePlatzhalter($header, $recipient, $token);
$body    = ersetzePlatzhalter($body, $recipient, $token);
$footer  = ersetzePlatzhalter($footer, $recipient, $token);
$subject = ersetzePlatzhalter($subject, $recipient, $token);

/* 3) Tracking-Links erzeugen */
$header  = ersetzeLinksMitTracking($header, (int)$data['id'], $db, $config['app']['base_url']);
$body    = ersetzeLinksMitTracking($body, (int)$data['id'], $db, $config['app']['base_url']);
$footer  = ersetzeLinksMitTracking($footer, (int)$data['id'], $db, $config['app']['base_url']);
?>
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title><?= htmlspecialchars($subject, ENT_QUOTES, 'UTF-8') ?></title>
  <style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    .email-container { border: 1px solid #ccc; padding: 20px; max-width: 700px; margin: auto; }
  </style>
</head>
<body>
  <div class="email-container">
    <?= $header ?>
    <?= $body ?>
    <?= $footer ?>
  </div>
</body>
</html>
