<?php
// =============================================================================
// Download — öffentlicher Endpoint für E-Mail-gegatete Downloads
// -----------------------------------------------------------------------------
// POST (JSON oder Form): token, email, newsletter → Lead anlegen + Download-Mail
// GET  ?t=<dl_token>   : per-Download-Token auflösen → 302 zur echten Datei
// =============================================================================

declare(strict_types=1);
require_once __DIR__ . '/spectronq/pv_config.php';
require_once __DIR__ . '/spectronq/_gated.php';

$dir = dirname(ALERTS_DB);
if (!is_dir($dir)) @mkdir($dir, 0755, true);
$db = new PDO('sqlite:' . ALERTS_DB);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
spq_gated_ensure_schema($db);

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

// ─────────────────────────────────────────────────────────────────────────────
// GET ?t=<dl_token> → Token auflösen, Zugriff protokollieren, zur Datei leiten.
// ─────────────────────────────────────────────────────────────────────────────
if ($method === 'GET' && isset($_GET['t'])) {
    $lead = spq_gated_consume($db, (string)$_GET['t']);
    if ($lead && (string)$lead['file_url'] !== '') {
        $target = (string)$lead['file_url'];
        // Relative URLs zu absoluten machen — robuster über Mail-Clients hinweg.
        if (!preg_match('#^https?://#i', $target)) {
            $target = rtrim(SPQ_NEWS_BASE_URL, '/') . '/' . ltrim($target, '/');
        }
        header('Location: ' . $target, true, 302);
        exit;
    }
    // Ungültig oder abgelaufen → freundliche Fehlerseite.
    spq_download_render_page('de', 'error',
        'Dieser Download-Link ist ungültig oder abgelaufen. / This download link is invalid or expired.');
    exit;
}

// ─────────────────────────────────────────────────────────────────────────────
// POST → Download anfordern (E-Mail erfassen + Mail versenden).
// ─────────────────────────────────────────────────────────────────────────────
if ($method === 'POST') {
    // JSON- ODER Form-Body akzeptieren.
    $raw  = file_get_contents('php://input');
    $json = null;
    if ($raw !== '' && strpos((string)($_SERVER['CONTENT_TYPE'] ?? ''), 'application/json') !== false) {
        $json = json_decode($raw, true);
    }
    $get = function (string $k, $default = '') use ($json) {
        if (is_array($json) && array_key_exists($k, $json)) return $json[$k];
        return $_POST[$k] ?? $default;
    };

    $isAjax = $json !== null || isset($_POST['ajax'])
        || strpos((string)($_SERVER['HTTP_ACCEPT'] ?? ''), 'application/json') !== false;

    $token      = (string)$get('token', '');
    $email      = (string)$get('email', '');
    $newsletter = (int)$get('newsletter', 0) === 1;
    $honeypot   = (string)$get('website', '');
    $ip         = (string)($_SERVER['REMOTE_ADDR'] ?? '');

    // Honeypot: stilles OK, ohne irgendetwas zu tun.
    if ($honeypot !== '') {
        spq_download_reply($isAjax, ['status' => 'ok', 'message' => 'OK']);
        exit;
    }

    // Rate-Limit (best effort): max. 20 Anfragen pro IP pro Stunde.
    if ($ip !== '') {
        $cutoff = time() - 3600;
        $cnt = $db->prepare('SELECT COUNT(*) FROM gated_leads WHERE ip = ? AND created_at > ?');
        $cnt->execute([$ip, $cutoff]);
        if ((int)$cnt->fetchColumn() > 20) {
            spq_download_reply($isAjax, ['status' => 'error',
                'message' => 'Zu viele Anfragen — bitte später erneut versuchen. / Too many requests — please try again later.']);
            exit;
        }
    }

    $res = spq_gated_request($db, $token, $email, $newsletter, $ip);

    // E-Mail-Serien auslösen, wenn die Download-Anfrage erfolgreich war.
    if (($res['status'] ?? '') === 'ok') {
        $file = spq_gated_resolve_file($db, $token);
        $fileLang = $file ? (string)$file['lang'] : 'de';
        require_once __DIR__ . '/spectronq/_series.php';
        @spq_series_enroll_event($db, 'gated', $email, $fileLang, $token);
    }

    spq_download_reply($isAjax, $res);
    exit;
}

// Default: keine Aktion → freundlicher Hinweis.
spq_download_render_page('de', 'error',
    'Kein Download angefordert. / No download requested.');
exit;

// =============================================================================
// Helper
// =============================================================================

/** AJAX → JSON, sonst HTML-Seite mit der Nachricht. */
function spq_download_reply(bool $isAjax, array $res): void {
    if ($isAjax) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($res);
        return;
    }
    $state = ($res['status'] ?? 'error') === 'ok' ? 'ok' : 'error';
    spq_download_render_page('de', $state, (string)($res['message'] ?? ''));
}

function spq_download_render_page(string $lang, string $state, string $message): void {
    $isEn  = $lang === 'en';
    $color = '#0d7373'; $bg = '#e8f4ee';
    if ($state === 'error') { $color = '#b0413e'; $bg = '#fde9e7'; }
    header('Content-Type: text/html; charset=utf-8');
    ?><!doctype html>
<html lang="<?= $isEn ? 'en' : 'de' ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,follow">
<title>Download — broschart.net</title>
<style>
  html,body{margin:0;padding:0;background:#ebe9e1;font-family:'Plus Jakarta Sans',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;color:#0d1410}
  .wrap{max-width:520px;margin:80px auto 40px;background:#fff;border-radius:16px;padding:48px 44px;box-shadow:0 20px 50px rgba(13,20,16,.06);border:1px solid #ececec}
  h1{font-size:28px;letter-spacing:-0.02em;margin:0 0 18px;line-height:1.15}
  .flash{background:<?= $bg ?>;color:#0d3030;border-left:3px solid <?= $color ?>;padding:14px 18px;border-radius:8px;font-size:15px;line-height:1.55;margin:0 0 24px}
  .home{display:inline-block;margin-top:8px;font-size:13px;color:#0d7373;font-weight:600;text-decoration:none}
  .home:hover{text-decoration:underline}
</style>
</head>
<body>
<main class="wrap">
  <h1>Download</h1>
  <?php if ($message !== ''): ?>
    <div class="flash"><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></div>
  <?php endif; ?>
  <a href="/<?= $isEn ? 'en/articles/' : 'artikel/' ?>" class="home"><?= $isEn ? '← Back to articles' : '← Zurück zu den Artikeln' ?></a>
</main>
</body>
</html>
<?php
}
