<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
$settings = cms_settings();
$success = array_merge([
    'enabled' => true,
    'title' => 'Спасибо за заявку!',
    'text' => 'Мы скоро с вами свяжемся.',
    'details_template' => "Ваша бронь: {house}\nДаты: {checkin_ru} – {checkout_ru}\nМы свяжемся с вами.",
    'duration_ms' => 10000,
    'return_url' => '/index.php',
], $settings['booking_success'] ?? []);
function fmt(string $ymd): string {
    if ($ymd === '') return '—';
    try { return (new DateTimeImmutable($ymd))->format('d.m.Y'); } catch (Throwable $e) { return $ymd; }
}
function tpl(string $template, array $payload): string {
    return preg_replace_callback('/\{(\w+)\}/', static fn(array $m): string => (string)($payload[$m[1]] ?? ''), $template) ?? $template;
}

function normalize_return_url(string $url): string {
    $url = trim($url);
    if ($url === '' || $url === '/') {
        return '/index.php';
    }
    $parts = parse_url($url);
    if (is_array($parts) && !empty($parts['host'])) {
        $currentHost = strtolower((string)($_SERVER['HTTP_HOST'] ?? ''));
        if (strtolower((string)$parts['host']) !== $currentHost) {
            return '/index.php';
        }
    }
    return $url;
}
$payload = [
    'house' => trim((string)($_GET['house'] ?? '')),
    'checkin' => trim((string)($_GET['checkin'] ?? '')),
    'checkout' => trim((string)($_GET['checkout'] ?? '')),
];
$payload['checkin_ru'] = fmt($payload['checkin']);
$payload['checkout_ru'] = fmt($payload['checkout']);
$detailText = tpl((string)($success['details_template'] ?? ''), $payload);
$returnUrl = normalize_return_url((string)($success['return_url'] ?? '/index.php'));
$seconds = max(1, (int)ceil(((int)($success['duration_ms'] ?? 10000))/1000));
?><!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= e(($success['title'] ?? 'Спасибо за заявку') . ' — ' . ($settings['branding']['browser_title'] ?? SITE_NAME)) ?></title>
<link rel="icon" href="<?= e($settings['branding']['favicon'] ?? '/favicon.ico') ?>">
<link rel="stylesheet" href="/assets/app.css?v=72">
<style>body.booking-success-page{min-height:100vh;display:grid;place-items:center;background:linear-gradient(180deg,#f7f1e7,#efe3d0);padding:24px}.booking-success-page .booking-success-card{width:min(720px,calc(100vw - 32px));padding:34px 32px 28px}.booking-success-page .booking-success-card__text{font-size:18px}.booking-success-page .booking-success-card__actions{display:flex;gap:12px;justify-content:center;flex-wrap:wrap;margin-top:18px}@media (max-width:720px){body.booking-success-page{padding:16px}.booking-success-page .booking-success-card{padding:26px 18px 20px}.booking-success-page .booking-success-card__text{font-size:16px}}</style>
</head>
<body class="booking-success-page">
  <section class="booking-success-card" role="status" aria-live="polite">
    <div class="booking-success-card__icon">✓</div>
    <h1 class="booking-success-card__title"><?= e($success['title'] ?? 'Спасибо за заявку!') ?></h1>
    <p class="booking-success-card__text"><?= nl2br(e($detailText)) ?></p>
    <p class="booking-success-card__hint">Через <span id="success-seconds"><?= $seconds ?></span> сек. вы вернётесь на главную страницу.</p>
    <div class="booking-success-card__actions">
      <a class="button button--primary" href="<?= e($returnUrl) ?>">Вернуться сейчас</a>
    </div>
  </section>
<script>
(function(){
  var seconds = <?= $seconds ?>;
  var node = document.getElementById('success-seconds');
  var returnUrl = <?= json_encode($returnUrl, 320) ?>;
  setInterval(function(){ seconds--; if(node && seconds >= 0){ node.textContent = String(seconds); } if(seconds <= 0){ window.location.href = returnUrl; } },1000);
})();
</script>
</body>
</html>
