<?php

require __DIR__ . '/../bootstrap.php';

use KeyLair\Auth;
use KeyLair\ClaimService;
use KeyLair\Csrf;
use KeyLair\Database;
use KeyLair\Helpers;
use KeyLair\I18n;
use KeyLair\PageStyle;
use KeyLair\Platform;
use KeyLair\ProductPlatform;
use KeyLair\Settings;

Auth::requireLogin();

$id = (int) ($_GET['id'] ?? 0);
$pdo = Database::connection();
$stmt = $pdo->prepare('SELECT * FROM products WHERE id = :id');
$stmt->execute(['id' => $id]);
$product = $stmt->fetch();

if (!$product) {
    http_response_code(404);
    die(I18n::t('product_preview.product_not_found'));
}

// The editor's own "Preview claim page" button posts the form's current,
// possibly-unsaved field values here instead of just linking to this
// product's last-saved row -- same transforms product_form.php applies
// on an actual save (renderRichText, custom CSS validation, theme
// allowlist), just never written to the database. Media (cover image,
// screenshots, background) still comes from the last save regardless --
// those only ever change via a real file upload, so there's no "unsaved"
// version of them to preview.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['live_preview'])) {
    Csrf::requireValid();
    $product['name'] = trim($_POST['name'] ?? $product['name']);
    $product['intro_text'] = Helpers::renderRichText(trim($_POST['intro_text'] ?? ''));
    $product['outro_text'] = Helpers::renderRichText(trim($_POST['outro_text'] ?? ''));
    $customCssRaw = trim($_POST['custom_css'] ?? '');
    if ($customCssRaw !== '') {
        $cssCheck = PageStyle::validateInlineCss($customCssRaw);
        $product['custom_css'] = $cssCheck['ok'] ? $customCssRaw : $product['custom_css'];
    } else {
        $product['custom_css'] = null;
    }
    $themeRaw = trim($_POST['theme'] ?? '');
    $product['theme'] = ($themeRaw !== '' && in_array($themeRaw, Settings::THEMES, true)) ? $themeRaw : null;
}

// The theme override above only affects this page's own markup -- the
// actual stylesheets are separate requests to css.php, which resolves a
// product's theme fresh from the database and knows nothing about an
// unsaved change here. css.php's own admin-preview_theme parameter
// (built for Design page theme previews) reaches the same result: it
// takes priority over whatever a product's saved theme is. Only covers
// switching *to* a specific theme live -- switching back to "Inherit
// site theme" while previewing still shows whatever theme was last
// actually saved, same limitation an unsaved image change would have.
$stylesheetThemeParam = ($product['theme'] !== null) ? '&preview_theme=' . urlencode($product['theme']) : '';

$stock = ClaimService::platformStock((int) $product['id']);
$media = ClaimService::mediaForProduct((int) $product['id']);

$mediaItems = ClaimService::buildMediaShowcase($media, $product['cover_image_path'] ?? null);
?>
<!DOCTYPE html>
<html lang="<?= Helpers::e(I18n::locale()) ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= Helpers::e(I18n::t('product_preview.title_prefix')) ?><?= Helpers::e($product['name']) ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/assets/css/tokens.css?product_id=<?= (int) $product['id'] . Helpers::e($stylesheetThemeParam) ?>">
<link rel="stylesheet" href="/assets/css/product-page.css?product_id=<?= (int) $product['id'] . Helpers::e($stylesheetThemeParam) ?>">
<?= \KeyLair\Settings::faviconTag() ?>
<?php if (!empty($product['custom_css'])): ?>
<style><?= $product['custom_css'] ?></style>
<?php endif; ?>
<style>
  .__preview-banner{
    position:fixed; top:0; left:0; right:0; z-index:999;
    background:#000; color:#94c93d; font-family:'JetBrains Mono',monospace;
    font-size:11.5px; letter-spacing:0.06em; text-transform:uppercase;
    text-align:center; padding:8px; border-bottom:1px solid #2a3947;
  }
  body{padding-top:34px;}
</style>
</head>
<body>
<div class="__preview-banner">
  <?= Helpers::e(I18n::t('product_preview.banner_text')) ?><?php if (isset($_POST['live_preview'])): ?> <?= Helpers::e(I18n::t('product_preview.banner_unsaved_suffix')) ?><?php endif; ?>
</div>
<div class="page">
  <div class="crumb"><a href="product_form.php?id=<?= (int) $product['id'] ?>">&larr; <?= Helpers::e(I18n::t('product_preview.back_to_editor')) ?></a></div>
  <div class="brandbar"><?= \KeyLair\Settings::brandIcon() ?><?= Helpers::e(\KeyLair\Settings::siteName()) ?> <?= Helpers::e(I18n::t('product_preview.review_access')) ?></div>

  <?php if (!empty($mediaItems)): ?>
  <div class="media-showcase">
    <div class="media-main <?= $mediaItems[0]['type'] === 'shot' ? 'is-shot' : '' ?>" id="media-main">
      <?php if ($mediaItems[0]['type'] === 'video'): ?>
        <iframe src="<?= Helpers::e($mediaItems[0]['src']) ?>" style="width:100%;height:100%;border:0;border-radius:inherit;position:relative;z-index:1;" allowfullscreen loading="lazy"></iframe>
      <?php else: ?>
        <img src="<?= Helpers::e($mediaItems[0]['src']) ?>" alt="" style="width:100%;height:100%;object-fit:cover;border-radius:inherit;position:relative;z-index:1;">
      <?php endif; ?>
    </div>
    <div class="media-thumbs">
      <?php foreach ($mediaItems as $i => $item): ?>
        <div class="thumb <?= $item['type'] ?> <?= $i === 0 ? 'active' : '' ?>"
             data-type="<?= $item['type'] ?>"
             data-src="<?= Helpers::e($item['src']) ?>"
             onclick="showMedia(this)">
          <?php if ($item['type'] === 'video'): ?>
            <span class="thumb-play"><svg viewBox="0 0 24 24" fill="#17212e"><path d="M8 5v14l11-7z"/></svg></span>
          <?php else: ?>
            <img src="<?= Helpers::e($item['src']) ?>" alt="" style="width:100%;height:100%;object-fit:cover;border-radius:inherit;">
          <?php endif; ?>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <div class="hero">
    <h1><?= Helpers::e($product['name']) ?></h1>
  </div>

  <?php if (!empty($product['intro_text'])): ?>
  <div class="text-block">
    <p class="text-block-label"><?= Helpers::e(I18n::t('product_preview.intro_label')) ?></p>
    <?= Helpers::renderRichText($product['intro_text']) ?>
  </div>
  <?php endif; ?>

  <p class="section-label"><?= Helpers::e(I18n::t('product_preview.section_label_platform')) ?></p>
  <div class="grid">
    <?php $supportedSlugs = ProductPlatform::supportedSlugs((int) $product['id']); ?>
    <?php foreach (Platform::groupForClaimPage($supportedSlugs) as $entry): ?>
      <?php if ($entry['type'] === 'single'):
          $available = ($stock[$entry['slug']] ?? 0) > 0;
      ?>
        <div class="tile <?= $available ? '' : 'disabled' ?>"><?= Platform::tileInner($entry['slug'], $available) ?></div>
      <?php else:
          $groupAvailable = Platform::groupAvailableCount($entry['slugs'], $stock) > 0;
      ?>
        <details class="tile-group <?= $groupAvailable ? '' : 'disabled' ?>">
          <summary class="tile-group-summary">
            <span class="tile-icon"><?= Platform::icon($entry['slugs'][0]) ?></span>
            <span class="tile-info">
              <span class="tile-name"><?= Helpers::e($entry['label']) ?></span>
              <span class="tile-status"><?= Helpers::e(Platform::groupStatusLabel($entry['slugs'], $stock)) ?></span>
            </span>
            <svg class="group-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
          </summary>
          <div class="tile-group-body">
            <?php foreach ($entry['slugs'] as $platform):
                $available = ($stock[$platform] ?? 0) > 0;
            ?>
              <div class="tile <?= $available ? '' : 'disabled' ?>"><?= Platform::tileInner($platform, $available) ?></div>
            <?php endforeach; ?>
          </div>
        </details>
      <?php endif; ?>
    <?php endforeach; ?>
  </div>
  <p style="text-align:center; color:var(--text-faint); font-size:12px; margin-top:10px;"><?= Helpers::e(I18n::t('product_preview.platform_tiles_notice')) ?></p>

  <?php if (!empty($product['outro_text'])): ?>
  <div class="text-block" style="margin-top:28px;">
    <p class="text-block-label"><?= Helpers::e(I18n::t('product_preview.outro_label')) ?></p>
    <?= Helpers::renderRichText($product['outro_text']) ?>
  </div>
  <?php endif; ?>

  <footer>
    <?= Helpers::e(I18n::t('product_preview.powered_by_prefix')) ?><a href="https://www.keylair.com" target="_blank" rel="noopener"><?= Helpers::e(\KeyLair\Settings::siteName()) ?></a><br>
    <a href="/imprint"><?= Helpers::e(I18n::t('product_preview.imprint')) ?></a> · <a href="/privacy"><?= Helpers::e(I18n::t('product_preview.privacy')) ?></a>
  </footer>
</div>

<script>
  function showMedia(el){
    document.querySelectorAll('.thumb').forEach(t => t.classList.remove('active'));
    el.classList.add('active');
    const main = document.getElementById('media-main');
    const type = el.dataset.type;
    const src = el.dataset.src;
    main.classList.toggle('is-shot', type === 'shot');
    if(type === 'video'){
      main.innerHTML = '<iframe src="'+src+'" style="width:100%;height:100%;border:0;border-radius:inherit;position:relative;z-index:1;" allowfullscreen loading="lazy"></iframe>';
    } else {
      main.innerHTML = '<img src="'+src+'" alt="" style="width:100%;height:100%;object-fit:cover;border-radius:inherit;position:relative;z-index:1;">';
    }
  }
</script>
</body>
</html>
