<?php
/**
 * Heritage Voice — site-og.php
 * Social share proxy cho di tích
 * URL: /site-og.php?id=...
 */
require_once __DIR__ . '/api/config.php';
require_once __DIR__ . '/api/db.php';

$id   = trim($_GET['id'] ?? '');
$base = 'https://tads.ctv.hanoi.vn';

$title = 'Heritage Voice — Khám phá di sản Việt Nam';
$desc  = 'Ứng dụng du lịch di sản văn hóa Việt Nam với thuyết minh audio tự động.';
$image = $base . '/assets/og-default.jpg';
$url   = $base . '/detail.html?site=' . htmlspecialchars($id);

if ($id) {
    $stmt = db()->prepare("SELECT name, description_short, cover_image, province_name FROM heritage_sites WHERE id = :id AND status = 'active'");
    $stmt->execute([':id' => $id]);
    $s = $stmt->fetch();

    if ($s) {
        $title = htmlspecialchars($s['name']) . ' — Heritage Voice';
        $desc  = $s['description_short']
            ? htmlspecialchars(mb_substr($s['description_short'], 0, 160))
            : htmlspecialchars($s['province_name'] ?? '');
        if (!empty($s['cover_image'])) $image = htmlspecialchars($s['cover_image']);
    }
}

$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$isCrawler = preg_match('/facebookexternalhit|Twitterbot|LinkedInBot|WhatsApp|Slackbot|TelegramBot|Zalobot|googlebot|bingbot/i', $ua);

if (!$isCrawler && $id) {
    header('Location: ' . $url);
    exit;
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8"/>
<meta property="og:type"        content="website"/>
<meta property="og:url"         content="<?= $base.'/site-og.php?id='.htmlspecialchars($id) ?>"/>
<meta property="og:title"       content="<?= $title ?>"/>
<meta property="og:description" content="<?= $desc ?>"/>
<meta property="og:image"       content="<?= $image ?>"/>
<meta property="og:image:width" content="1200"/>
<meta property="og:image:height"content="630"/>
<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:description"content="<?= $desc ?>"/>
<meta name="twitter:image"      content="<?= $image ?>"/>
<title><?= $title ?></title>
<meta http-equiv="refresh" content="0;url=<?= $url ?>"/>
</head>
<body>
<script>window.location.replace('<?= $url ?>');</script>
</body>
</html>
