<?php
declare(strict_types=1);

$cfg = require __DIR__ . '/../config.php';
require_once __DIR__ . '/../lib/content_drafts.php';

function html_error(int $status, string $message): never {
  http_response_code($status);
  header('Content-Type: text/html; charset=utf-8');
  echo <<<HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Draft Preview</title>
  <style>
    body { font-family: system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; margin: 2rem; background:#f5f5f7; color:#111; }
    .card { max-width: 900px; margin: 0 auto; background:#fff; border:1px solid #d0d0d5; box-shadow:0 2px 8px rgba(15,15,40,.08); padding:2rem; border-radius:1rem; }
    .error { color:#b00020; }
  </style>
</head>
<body>
  <div class="card">
    <h1 class="error">{$message}</h1>
    <p>Status: {$status}</p>
  </div>
</body>
</html>
HTML;
  exit;
}

$ref = trim((string)($_GET['ref'] ?? ''));
$draftId = trim((string)($_GET['draft'] ?? ''));
$token = trim((string)($_GET['token'] ?? ''));

if ($ref === '' || $draftId === '') {
  html_error(400, 'Missing preview parameters');
}
if ($token === '') {
  html_error(403, 'Missing preview token');
}

if (!preg_match('/^t_[a-f0-9]{16}$/', $ref)) {
  html_error(400, 'Invalid tenant_ref');
}

$paths = tenant_paths($cfg, $ref);
if (!is_dir($paths['tenantDir'])) {
  html_error(404, 'Tenant not found');
}

$draft = content_read_draft($cfg, $ref, $draftId);
if (!is_array($draft)) {
  html_error(404, 'Draft not found');
}

$preview = trim((string)($draft['preview_token'] ?? ''));
if ($preview === '' || !hash_equals($preview, $token)) {
  html_error(403, 'Invalid preview token');
}

$previewTtl = (int)($cfg['preview_token_ttl_secs'] ?? 604800);
if ($previewTtl <= 0) {
  $previewTtl = 604800;
}
$expiresAt = null;
$previewExpires = trim((string)($draft['preview_expires_at'] ?? ''));
if ($previewExpires !== '') {
  $expiresAt = strtotime($previewExpires);
}
if ($expiresAt === false || $expiresAt === null) {
  $createdTs = strtotime((string)($draft['created_at'] ?? ''));
  if ($createdTs !== false) {
    $expiresAt = $createdTs + $previewTtl;
  }
}
if ($expiresAt === null) {
  html_error(403, 'Invalid preview token');
}
if ($expiresAt < time()) {
  html_error(403, 'Expired preview token');
}

$title = htmlspecialchars((string)($draft['title'] ?? 'Draft Preview'), ENT_QUOTES, 'UTF-8');
$status = htmlspecialchars((string)($draft['status'] ?? 'generated'), ENT_QUOTES, 'UTF-8');
$created = htmlspecialchars((string)($draft['created_at'] ?? ''), ENT_QUOTES, 'UTF-8');
$bodyHtml = $draft['html'] ?? '<p>No content available.</p>';
$plain = htmlspecialchars((string)($draft['plaintext_excerpt'] ?? ''), ENT_QUOTES, 'UTF-8');
$social = is_array($draft['social_snippets'] ?? null) ? $draft['social_snippets'] : [];
$captionShort = htmlspecialchars((string)($social['caption_short'] ?? ''), ENT_QUOTES, 'UTF-8');
$captionLong = htmlspecialchars((string)($social['caption_long'] ?? ''), ENT_QUOTES, 'UTF-8');
$hashtags = is_array($social['hashtags'] ?? null) ? $social['hashtags'] : [];
$tags = htmlspecialchars(implode(' ', $hashtags), ENT_QUOTES, 'UTF-8');

header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');
header("Content-Security-Policy: default-src 'none'; style-src 'self' 'unsafe-inline'; font-src 'self';");
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('Referrer-Policy: no-referrer');

echo <<<HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{$title}</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
    :root { color-scheme: light; }
    body { margin:0; font-family: system-ui,-apple-system,"Segoe UI",sans-serif; background:#f3f4f6; color:#0f172a; }
    .shell { min-height:100vh; padding:2rem; }
    .card { max-width:960px; margin:0 auto; background:#fff; border-radius:1rem; box-shadow:0 1rem 3rem rgba(15,23,42,0.1); padding:2rem; }
    .preview-html { margin-top:1rem; padding-top:1rem; border-top:1px solid rgba(15,23,42,0.08); }
    .meta { font-size:.9rem; color:#475569; margin-top:1rem; }
    .meta b { color:#0f172a; }
    .social { margin-top:1rem; background:#f8fafc; padding:1rem; border-radius:.75rem; }
    .social strong { display:block; margin-bottom:.4rem; }
    pre { background:#111827; color:#e2e8f0; padding:1rem; border-radius:.75rem; overflow:auto; }
  </style>
</head>
<body>
  <div class="shell">
    <div class="card">
      <header>
        <p class="meta">Tenant <b>{$ref}</b> · Draft <b>{$draftId}</b></p>
        <h1>{$title}</h1>
        <p class="meta">Status: <b>{$status}</b> · Created: <b>{$created}</b></p>
      </header>
      <section class="preview-html">
        {$bodyHtml}
      </section>
      <section class="social">
        <strong>Plaintext excerpt</strong>
        <pre>{$plain}</pre>
        <strong>Caption (preview)</strong>
        <p>{$captionShort}</p>
        <strong>Caption (long)</strong>
        <p>{$captionLong}</p>
        <strong>Hashtags</strong>
        <p>{$tags}</p>
      </section>
    </div>
  </div>
</body>
</html>
HTML;
