<?php
$base = '/home/tranhiep/tads.ctv.hanoi.vn';
require_once $base . '/api/config.php';
require_once $base . '/api/db.php';

$slug = preg_replace('/[^a-z0-9_-]/', '', $_GET['site'] ?? '');
if (!$slug) { header('Location: /home.html'); exit; }

$stmt = db()->prepare("
    SELECT hs.id, hs.name, hs.slug, hs.description_short, hs.cover_image,
           hs.type, hs.latitude, hs.longitude, p.name_new AS province_name
    FROM heritage_sites hs
    LEFT JOIN provinces p ON p.id = hs.province_id
    WHERE (hs.id = :s1 OR hs.slug = :s2) AND hs.status = 'active'
    LIMIT 1
");
$stmt->execute(array(':s1' => $slug, ':s2' => $slug));
$site = $stmt->fetch();

if (!$site) { header('Location: /home.html'); exit; }

$title       = htmlspecialchars($site['name']) . ' – Heritage Voice';
$description = htmlspecialchars($site['description_short'] ?? 'Khám phá di sản văn hóa Việt Nam qua thuyết minh audio.');
$image       = $site['cover_image'] ? htmlspecialchars($site['cover_image']) : 'https://tads.ctv.hanoi.vn/assets/icon-512.png';
$canonical   = 'https://tads.ctv.hanoi.vn/' . ($site['slug'] ?: $site['id']);
$siteData    = addslashes(json_encode(array(
    'id'                => $site['id'],
    'name'              => $site['name'],
    'slug'              => $site['slug'],
    'description_short' => $site['description_short'],
    'cover_image'       => $site['cover_image'],
    'type'              => $site['type'],
    'latitude'          => (float)$site['latitude'],
    'longitude'         => (float)$site['longitude'],
    'province_name'     => $site['province_name'],
), JSON_UNESCAPED_UNICODE));

// Đọc nội dung detail.html và inject vào
$detailHtml = file_get_contents($base . '/detail.html');

// Inject meta tags SEO vào <head>
$metaTags = '
<title>' . $title . '</title>
<meta name="description" content="' . $description . '"/>
<link rel="canonical" href="' . $canonical . '"/>
<meta property="og:type" content="place"/>
<meta property="og:title" content="' . $title . '"/>
<meta property="og:description" content="' . $description . '"/>
<meta property="og:image" content="' . $image . '"/>
<meta property="og:url" content="' . $canonical . '"/>
<meta property="og:site_name" content="Heritage Voice"/>
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:title" content="' . $title . '"/>
<meta name="twitter:image" content="' . $image . '"/>
<script>
try{sessionStorage.setItem("hv_site","' . $siteData . '");}catch(e){}
</script>';

// Thay thế <title> cũ và inject vào trước </head>
$detailHtml = preg_replace('/<title>[^<]*<\/title>/', '', $detailHtml);
$detailHtml = str_replace('</head>', $metaTags . '</head>', $detailHtml);

echo $detailHtml;
