<?php
/**
 * 中国农业网 — 动态 SEO 入口
 * 从 config.js 读取 Supabase 配置 → 调用 REST API 获取 site_settings → 输出带正确 meta 的首页 HTML
 * 宝塔部署后 Nginx 将 SPA 回退改为 /index.php，本文件替代静态 index.html
 */

// ── 1. 从 config.js 解析 Supabase 配置 ──────────────────────────────────────
$configFile = __DIR__ . '/config.js';
$supabaseUrl = '';
$supabaseKey = '';

if (file_exists($configFile)) {
    $js = file_get_contents($configFile);
    // 解析 supabaseUrl: "..."
    if (preg_match('/supabaseUrl\s*:\s*["\']([^"\']+)["\']/', $js, $m)) {
        $supabaseUrl = rtrim($m[1], '/');
    }
    // 解析 supabaseAnonKey: "..."
    if (preg_match('/supabaseAnonKey\s*:\s*["\']([^"\']+)["\']/', $js, $m)) {
        $supabaseKey = $m[1];
    }
}

// ── 2. 从 Supabase REST API 获取 SEO 配置（带 1s 缓存） ────────────────────
$seo = [];

if ($supabaseUrl && $supabaseKey) {
    $cacheFile = sys_get_temp_dir() . '/seo_cache_' . md5($supabaseUrl) . '.json';
    $cacheTtl  = 60; // 缓存60秒，后台保存后最多1分钟生效

    // 读缓存
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTtl) {
        $cached = json_decode(file_get_contents($cacheFile), true);
        if (is_array($cached)) $seo = $cached;
    }

    // 缓存过期或不存在则重新拉取
    if (empty($seo) && function_exists('curl_init')) {
        $apiUrl = $supabaseUrl . '/rest/v1/site_settings?select=key,value&key=like.seo_home_%';
        $ch = curl_init($apiUrl);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 3,
            CURLOPT_HTTPHEADER     => [
                'apikey: '          . $supabaseKey,
                'Authorization: Bearer ' . $supabaseKey,
                'Accept: application/json',
            ],
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $resp = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($code === 200 && $resp) {
            $rows = json_decode($resp, true);
            if (is_array($rows)) {
                foreach ($rows as $row) {
                    $seo[$row['key']] = $row['value'];
                }
                file_put_contents($cacheFile, json_encode($seo));
            }
        }
    }

    // 同时拉取 site_name / og_image / og_url
    if (function_exists('curl_init')) {
        $extraKeys = ['site_name','og_image','og_url','site_icp','site_copyright'];
        $keyFilter  = 'key=in.(' . implode(',', $extraKeys) . ')';
        $apiUrl2 = $supabaseUrl . '/rest/v1/site_settings?select=key,value&' . $keyFilter;
        $ch2 = curl_init($apiUrl2);
        curl_setopt_array($ch2, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 3,
            CURLOPT_HTTPHEADER     => [
                'apikey: '          . $supabaseKey,
                'Authorization: Bearer ' . $supabaseKey,
                'Accept: application/json',
            ],
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $resp2 = curl_exec($ch2);
        $code2 = curl_getinfo($ch2, CURLINFO_HTTP_CODE);
        curl_close($ch2);
        if ($code2 === 200 && $resp2) {
            $rows2 = json_decode($resp2, true);
            if (is_array($rows2)) {
                foreach ($rows2 as $row) {
                    $seo[$row['key']] = $row['value'];
                }
            }
        }
    }
}

// ── 3. 兜底默认值 ───────────────────────────────────────────────────────────
function e(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

$title       = e($seo['seo_home_title']       ?? '中国农业网 - 农产品B2B交易平台');
$description = e($seo['seo_home_description'] ?? '中国农业网是专业的农产品B2B交易平台，汇聚全国粮食、蔬菜、水果等农产品供需信息。');
$keywords    = e($seo['seo_home_keywords']    ?? '中国农业网,农产品B2B,粮食批发,蔬菜供应,水果批发');
$siteName    = e($seo['site_name']            ?? '中国农业网');
$ogImage     = e($seo['og_image']             ?? 'https://miaoda-site-img.cdn.bcebos.com/images/baidu_image_search_45e1e014-0dcc-42e3-a319-ebfc7726c15b.jpg');
$ogUrl       = e($seo['og_url']               ?? 'https://congnong.com');

// ── 4. 读取 assets 文件名（每次构建哈希不同） ─────────────────────────────
$assetsDir = __DIR__ . '/assets';
$jsFile    = '';
$cssFile   = '';

if (is_dir($assetsDir)) {
    foreach (scandir($assetsDir) as $f) {
        if (str_starts_with($f, 'index-') && str_ends_with($f, '.js'))  $jsFile  = '/assets/' . $f;
        if (str_starts_with($f, 'index-') && str_ends_with($f, '.css')) $cssFile = '/assets/' . $f;
    }
}

?><!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <link rel="icon" type="image/svg+xml" href="/favicon.png" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title><?= $title ?></title>
  <meta name="keywords"    content="<?= $keywords ?>" />
  <meta name="description" content="<?= $description ?>" />
  <!-- Open Graph / 微信朋友圈分享 -->
  <meta property="og:type"        content="website" />
  <meta property="og:site_name"   content="<?= $siteName ?>" />
  <meta property="og:title"       content="<?= $title ?>" />
  <meta property="og:description" content="<?= $description ?>" />
  <meta property="og:image"       content="<?= $ogImage ?>" />
  <meta property="og:image:width"  content="1200" />
  <meta property="og:image:height" content="630" />
  <meta property="og:image:type"   content="image/jpeg" />
  <meta property="og:url"         content="<?= $ogUrl ?>" />
  <meta property="og:locale"      content="zh_CN" />
  <!-- Twitter Card -->
  <meta name="twitter:card"        content="summary_large_image" />
  <meta name="twitter:title"       content="<?= $title ?>" />
  <meta name="twitter:description" content="<?= $description ?>" />
  <meta name="twitter:image"       content="<?= $ogImage ?>" />
  <!-- 百度搜索优化 -->
  <meta name="robots"  content="index, follow" />
  <meta name="author"  content="<?= $siteName ?>" />
  <!-- 运行时配置，由 install.php 安装器写入 -->
  <script src="/config.js"></script>
<?php if ($cssFile): ?>
  <link rel="stylesheet" crossorigin href="<?= $cssFile ?>">
<?php endif; ?>
</head>
<body>
  <div id="root"></div>
<?php if ($jsFile): ?>
  <script type="module" crossorigin src="<?= $jsFile ?>"></script>
<?php else: ?>
  <!-- 降级：找不到 assets 时加载 config.js 后靠 SPA 自行路由 -->
<?php endif; ?>
</body>
</html>
