<?php
/**
 * TG4G English homepage (/en/ and /en/index.php)
 *
 * - Hero positioned for overseas SaaS / VPS / Payment audiences
 * - "China Accessibility Rating" + "49,374 vendors / 19,000+ AI reviews" social proof
 * - Top 17 category nav
 * - Top-rated providers card grid (pulled live from listings table)
 *
 * Deploy to: /var/www/tg4g/public/en/index.php
 */
declare(strict_types=1);

require_once __DIR__ . '/i18n.php';

$cfg = require '/var/www/tg4g/config.php';
$db = $cfg['database'];
$dsn = 'mysql:host=' . $db['host'] . ';port=' . ($db['port'] ?? 3306) . ';dbname=' . $db['database'] . ';charset=utf8mb4';
$pdo = new PDO($dsn, $db['username'], $db['password'], [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

function h($s) { return htmlspecialchars((string)($s ?? ''), ENT_QUOTES|ENT_HTML5, 'UTF-8'); }

// Categories in display order
$CATS = [
    'vps'       => ['VPS', '🖥', 'Virtual Private Servers'],
    'dedicated' => ['Dedicated', '🗄', 'Bare-metal & colocation'],
    'cdn'       => ['CDN', '🌐', 'Content delivery & edge'],
    'payment'   => ['Payments', '💳', 'Cross-border & virtual cards'],
    'proxy'     => ['Proxies', '🔌', 'Residential / DC / mobile'],
    'domain'    => ['Domains', '🌍', 'Registrars & TLDs'],
    'saas'      => ['SaaS', '⚙', 'Productivity tools'],
    'ai'        => ['AI Apps', '🤖', 'LLMs, APIs & agents'],
    'edu'       => ['Education', '📚', 'Courses & MOOCs'],
    'dev'       => ['Dev Tools', '🔧', 'APIs, SDKs, DevOps'],
    'crypto'    => ['Crypto', '💰', 'Exchanges, wallets, DeFi'],
    'marketing' => ['Marketing & SEO', '📈', 'SEO, ads, analytics'],
    'design'    => ['Design & Creative', '🎨', 'UI/UX & stock assets'],
    'security'  => ['Security', '🛡', 'SSL, IAM, pen-test'],
    'biz'       => ['Incorp & Compliance', '📋', 'Company formation & tax'],
    'comm'      => ['Comms & Email', '✉', 'Email, SMS, OTP'],
    'ec'        => ['E-commerce', '🛒', 'Shopify, dropshipping'],
];

// Category counts (live)
$cat_counts = [];
foreach ($pdo->query("SELECT category, COUNT(*) AS n FROM listings WHERE is_active=1 GROUP BY category")->fetchAll() as $r) {
    $cat_counts[$r['category']] = (int)$r['n'];
}
$total_all = array_sum($cat_counts);

// Total review count (live)
$total_reviews = (int)$pdo->query("SELECT COUNT(*) FROM listings WHERE is_active=1 AND review_cn IS NOT NULL AND review_cn <> ''")->fetchColumn();

// Top-rated providers per category (1-2 per cat, rating_avg DESC, hi review_count tiebreak)
$top_rated_sql = "
    SELECT id, provider, plan_name, category, sub_category, hq_country,
           price_monthly_usd, rating_avg, review_count, cn_friendly, badge
    FROM (
        SELECT *,
               ROW_NUMBER() OVER (PARTITION BY category ORDER BY rating_avg DESC, review_count DESC) AS rn
        FROM listings
        WHERE is_active=1 AND rating_avg >= 7
    ) t
    WHERE rn <= 2
    ORDER BY rating_avg DESC, review_count DESC
    LIMIT 24
";
try {
    $top_rated = $pdo->query($top_rated_sql)->fetchAll();
} catch (Throwable $e) {
    // MariaDB without window functions: fallback to plain ORDER BY
    $top_rated = $pdo->query("SELECT id, provider, plan_name, category, sub_category, hq_country, price_monthly_usd, rating_avg, review_count, cn_friendly, badge FROM listings WHERE is_active=1 AND rating_avg >= 8 ORDER BY rating_avg DESC, review_count DESC LIMIT 24")->fetchAll();
}

// Most recently added
$recent = $pdo->query("SELECT id, provider, plan_name, category, sub_category, rating_avg, price_monthly_usd FROM listings WHERE is_active=1 ORDER BY id DESC LIMIT 12")->fetchAll();

// Dataset last updated (for header chrome)
$dataset_updated = $pdo->query("SELECT MAX(updated_at) FROM listings WHERE is_active=1")->fetchColumn();

// SEO
$site_title = t('site_title_en');
$site_desc  = t('site_desc_en');
$canonical  = 'https://tg4g.com/en/';
$zh_alt     = 'https://tg4g.com/';

// JSON-LD: WebSite + ItemList (top picks)
$site_ld = [
    '@context' => 'https://schema.org',
    '@type'    => 'WebSite',
    'name'     => 'TG4G - Overseas SaaS & Infra Reviews',
    'url'      => $canonical,
    'inLanguage' => 'en',
    'description' => $site_desc,
    'potentialAction' => [
        '@type' => 'SearchAction',
        'target' => 'https://tg4g.com/en/listings?q={search_term_string}',
        'query-input' => 'required name=search_term_string',
    ],
];
$itemlist_ld = [
    '@context' => 'https://schema.org',
    '@type'    => 'ItemList',
    'name'     => 'Top-rated overseas providers',
    'inLanguage' => 'en',
    'itemListElement' => array_map(function ($i, $r) {
        return [
            '@type'    => 'ListItem',
            'position' => $i + 1,
            'url'      => 'https://tg4g.com/en/listing/' . (int)$r['id'],
            'name'     => $r['provider'],
        ];
    }, array_keys($top_rated), $top_rated),
];
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= h($site_title) ?></title>
<meta name="description" content="<?= h($site_desc) ?>">
<link rel="canonical" href="<?= h($canonical) ?>">
<link rel="alternate" hreflang="en"    href="<?= h($canonical) ?>">
<link rel="alternate" hreflang="zh-CN" href="<?= h($zh_alt) ?>">
<link rel="alternate" hreflang="x-default" href="<?= h($canonical) ?>">
<meta property="og:type" content="website">
<meta property="og:locale" content="en_US">
<meta property="og:locale:alternate" content="zh_CN">
<meta property="og:title" content="<?= h($site_title) ?>">
<meta property="og:description" content="<?= h($site_desc) ?>">
<meta property="og:url" content="<?= h($canonical) ?>">
<meta property="og:image" content="https://tg4g.com/assets/tg4g-og.png">
<meta property="og:site_name" content="TG4G Overseas Directory">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://tg4g.com/assets/tg4g-og.png">
<script type="application/ld+json"><?= json_encode($site_ld, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?></script>
<script type="application/ld+json"><?= json_encode($itemlist_ld, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?></script>
<style>
*{box-sizing:border-box}
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Inter,sans-serif;margin:0;background:#f5f7fa;color:#1e293b;font-size:14px;line-height:1.55}
a{color:#2563eb;text-decoration:none}
a:hover{text-decoration:underline}
header{background:linear-gradient(135deg,#0f172a,#1e3a8a);color:#f1f5f9;padding:0}
.topnav{max-width:1280px;margin:0 auto;padding:0 16px;display:flex;align-items:center;flex-wrap:wrap;min-height:54px}
.brand{display:flex;align-items:center;padding:11px 18px 11px 0;font-size:18px;font-weight:700;color:#fff;text-decoration:none;white-space:nowrap}
.brand .b-sub{font-size:11px;font-weight:400;color:#94a3b8;margin-left:10px}
.topnav .l{margin-left:auto;display:flex;align-items:center;gap:10px}
.topnav .l a{color:#cbd5e1;font-size:12px;padding:6px 10px;border-radius:4px}
.topnav .l a:hover{background:rgba(255,255,255,.07);color:#fff;text-decoration:none}
.topnav .l a.cta{background:#2563eb;color:#fff;font-weight:600}
.topnav .l a.lang{background:rgba(255,255,255,.07);font-size:11px;padding:4px 8px}
.topnav .l a.lang.on{background:#60a5fa;color:#0f172a;font-weight:700}
.hero{background:linear-gradient(135deg,#0f172a 0%,#1e3a8a 60%,#3b82f6 100%);color:#f1f5f9;padding:48px 16px 60px;text-align:center}
.hero h1{margin:0 0 14px;font-size:38px;font-weight:800;letter-spacing:-1px;line-height:1.15}
.hero h1 .accent{color:#fbbf24}
.hero .sub{font-size:16px;color:#cbd5e1;margin:0 auto 22px;max-width:760px;line-height:1.6}
.hero .stats{display:flex;justify-content:center;gap:32px;flex-wrap:wrap;margin:24px auto 28px;max-width:780px}
.hero .stat{background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.15);border-radius:10px;padding:14px 22px;min-width:160px}
.hero .stat .n{font-size:28px;font-weight:800;color:#fbbf24;line-height:1}
.hero .stat .l{font-size:11px;color:#cbd5e1;margin-top:4px;text-transform:uppercase;letter-spacing:.7px}
.hero .ctas{display:flex;gap:12px;justify-content:center;flex-wrap:wrap}
.hero .ctas a{padding:12px 26px;border-radius:6px;font-size:14px;font-weight:600;text-decoration:none}
.hero .ctas a.primary{background:#fbbf24;color:#0f172a}
.hero .ctas a.primary:hover{background:#f59e0b}
.hero .ctas a.secondary{background:rgba(255,255,255,.1);color:#fff;border:1px solid rgba(255,255,255,.2)}
.hero .ctas a.secondary:hover{background:rgba(255,255,255,.16)}
.container{max-width:1280px;margin:0 auto;padding:30px 16px}
.section-h{font-size:22px;font-weight:700;color:#0f172a;margin:0 0 4px;display:flex;align-items:center;gap:10px}
.section-sub{color:#64748b;font-size:13px;margin:0 0 18px}
.section-h .count{font-size:14px;color:#2563eb;font-weight:500}
.cat-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin-bottom:38px}
.cat-card{display:block;background:#fff;border-radius:8px;padding:16px 14px;color:#0f172a;text-decoration:none;border:1px solid #e2e8f0;transition:transform .12s,border-color .12s,box-shadow .12s}
.cat-card:hover{border-color:#2563eb;box-shadow:0 4px 14px rgba(37,99,235,.10);transform:translateY(-2px);text-decoration:none}
.cat-card .ic{font-size:26px;line-height:1}
.cat-card .nm{font-weight:700;font-size:14px;margin-top:8px}
.cat-card .desc{font-size:11px;color:#64748b;margin-top:3px;line-height:1.4;min-height:32px}
.cat-card .cnt{font-size:11px;color:#2563eb;font-weight:600;margin-top:6px}
.prov-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px;margin-bottom:38px}
.prov-card{background:#fff;border-radius:8px;padding:16px;border:1px solid #e2e8f0;display:flex;flex-direction:column;justify-content:space-between;min-height:160px}
.prov-card .top{display:flex;justify-content:space-between;align-items:flex-start;gap:8px}
.prov-card .nm{font-size:16px;font-weight:700;color:#0f172a;text-decoration:none}
.prov-card .nm:hover{color:#2563eb}
.prov-card .rating{font-size:13px;color:#f59e0b;font-weight:700;white-space:nowrap}
.prov-card .meta{color:#64748b;font-size:11px;margin-top:6px;line-height:1.6}
.prov-card .meta .bdg{display:inline-block;padding:1px 7px;border-radius:10px;background:#e0e7ff;color:#3730a3;font-size:10px;margin-right:4px}
.prov-card .row{display:flex;justify-content:space-between;align-items:center;margin-top:10px;font-size:11px;color:#64748b}
.prov-card .price{color:#16a34a;font-weight:700;font-size:14px}
.prov-card .cn{color:#f59e0b;letter-spacing:-1px;font-weight:700}
.prov-card a.cta{display:inline-block;margin-top:10px;background:#2563eb;color:#fff;padding:6px 12px;border-radius:4px;font-size:12px;font-weight:600;text-align:center;text-decoration:none}
.prov-card a.cta:hover{background:#1d4ed8;text-decoration:none}
.pill{display:inline-block;padding:1px 7px;border-radius:10px;background:#fee2e2;color:#991b1b;font-size:10px;font-weight:700;margin-left:4px}
.bullets{background:#fff;border-radius:8px;padding:24px;border:1px solid #e2e8f0;margin-bottom:30px}
.bullets h3{margin:0 0 14px;font-size:18px}
.bullets ul{list-style:none;padding:0;margin:0;display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:14px 28px}
.bullets li{padding-left:26px;position:relative;font-size:13px;color:#334155;line-height:1.55}
.bullets li::before{content:"✓";position:absolute;left:0;top:0;color:#16a34a;font-weight:900;font-size:16px}
.bullets li strong{color:#0f172a}
.recent-list{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:0;margin-bottom:30px;overflow:hidden}
.recent-list .item{display:flex;justify-content:space-between;align-items:center;padding:10px 16px;border-bottom:1px solid #f1f5f9}
.recent-list .item:last-child{border-bottom:0}
.recent-list .item:hover{background:#f8fafc}
.recent-list a{color:#0f172a;font-weight:600;font-size:13px}
.recent-list .meta{color:#64748b;font-size:11px}
.recent-list .right{color:#16a34a;font-weight:700;font-size:13px}
footer{background:#fff;border-top:1px solid #e2e8f0;padding:30px 16px;color:#64748b;text-align:center;font-size:12px}
footer a{color:#2563eb}
footer .links{margin-bottom:8px}
footer .links a{margin:0 8px}
@media (max-width:640px){
    .hero{padding:32px 14px 40px}
    .hero h1{font-size:26px}
    .hero .sub{font-size:14px}
    .hero .stat{padding:10px 14px;min-width:130px}
    .hero .stat .n{font-size:22px}
    .container{padding:20px 14px}
    .section-h{font-size:18px}
}
</style>
</head>
<body>

<header>
  <div class="topnav">
    <a class="brand" href="/en/">🚀 TG4G <span class="b-sub">Overseas SaaS & Infra Reviews</span></a>
    <div class="l">
      <a href="/en/listings">Directory</a>
      <a href="/en/listings?cat=vps">VPS</a>
      <a href="/en/listings?cat=payment">Payments</a>
      <a href="/en/listings?cat=ai">AI</a>
      <a class="cta" href="/en/listings">Browse all</a>
      <a class="lang on" href="/en/" hreflang="en">EN</a>
      <a class="lang" href="/" hreflang="zh-CN">中</a>
    </div>
  </div>
</header>

<section class="hero">
  <h1><?= h(t('hero_title_en')) ?></h1>
  <p class="sub"><?= h(t('hero_subtitle_en')) ?></p>
  <div class="stats">
    <div class="stat"><div class="n"><?= number_format($total_all) ?></div><div class="l">Vendors tracked</div></div>
    <div class="stat"><div class="n"><?= number_format($total_reviews) ?>+</div><div class="l">In-depth reviews</div></div>
    <div class="stat"><div class="n">17</div><div class="l">Categories</div></div>
    <div class="stat"><div class="n">★★★</div><div class="l">China-access rating</div></div>
  </div>
  <div class="ctas">
    <a class="primary" href="/en/listings"><?= h(t('cta_browse_all')) ?> →</a>
    <a class="secondary" href="/en/listings?cat=vps">Top VPS providers</a>
    <a class="secondary" href="/en/listings?cat=payment">Payment & virtual cards</a>
  </div>
</section>

<div class="container">

  <h2 class="section-h">📂 <?= h(t('browse_by_category')) ?> <span class="count">(<?= count($CATS) ?> categories)</span></h2>
  <p class="section-sub">Each category has its own filter profile (network type, datacenter, HQ, price, China-friendliness) tuned for that domain.</p>
  <div class="cat-grid">
    <?php foreach ($CATS as $k => [$lbl, $ic, $desc]):
        $cnt = $cat_counts[$k] ?? 0;
    ?>
      <a class="cat-card" href="/en/listings?cat=<?= h($k) ?>">
        <div class="ic"><?= $ic ?></div>
        <div class="nm"><?= h($lbl) ?></div>
        <div class="desc"><?= h($desc) ?></div>
        <div class="cnt"><?= number_format($cnt) ?> entries →</div>
      </a>
    <?php endforeach; ?>
  </div>

  <div class="bullets">
    <h3>What makes TG4G different</h3>
    <ul>
      <li><strong>China-Accessibility Rating.</strong> Every entry gets a 0-3 star score reflecting whether mainland China users can reach it without a proxy.</li>
      <li><strong>Multi-source data.</strong> Vendor official sites, Google AI Mode answers, Trustpilot signals and AI synthesis are combined into a single record.</li>
      <li><strong><?= number_format($total_reviews) ?>+ in-depth reviews.</strong> Long-form provider analyses based on public information.</li>
      <li><strong>Real pricing, no fluff.</strong> Monthly/yearly USD pricing pulled from vendor pages, plus refund windows and accepted payment methods.</li>
      <li><strong>Faceted filters.</strong> 9-axis filtering (network type, DC, CPU/RAM/disk/BW, price, rating, CN, refund, payment) per category.</li>
      <li><strong>CSV export & RSS.</strong> Take the data with you for spreadsheets or feed-readers.</li>
    </ul>
  </div>

  <h2 class="section-h">⭐ <?= h(t('featured_top')) ?> <span class="count">(rating ≥ 7.0)</span></h2>
  <p class="section-sub">Top-rated overseas providers across all 17 categories, sorted by rating and review count.</p>
  <div class="prov-grid">
    <?php foreach ($top_rated as $r):
        $cat_lbl = $CATS[$r['category']][0] ?? $r['category'];
    ?>
      <div class="prov-card">
        <div>
          <div class="top">
            <a class="nm" href="/en/listing/<?= (int)$r['id'] ?>"><?= h($r['provider']) ?></a>
            <span class="rating">★ <?= number_format((float)$r['rating_avg'], 1) ?></span>
          </div>
          <div class="meta">
            <span class="bdg"><?= h($cat_lbl) ?></span>
            <?php if ($r['sub_category']): ?><span class="bdg"><?= h(tsub($r['sub_category'])) ?></span><?php endif; ?>
            <?php if ($r['badge']): ?><span class="pill"><?= h($r['badge']) ?></span><?php endif; ?>
            <div style="margin-top:6px"><?= h($r['plan_name']) ?: '&nbsp;' ?></div>
            <?php if ($r['hq_country']): ?><div style="margin-top:3px">HQ: <?= h($r['hq_country']) ?></div><?php endif; ?>
          </div>
        </div>
        <div>
          <div class="row">
            <?php if ($r['price_monthly_usd']>0): ?>
              <span class="price">$<?= number_format((float)$r['price_monthly_usd'], 2) ?> / mo</span>
            <?php else: ?>
              <span>Pricing varies</span>
            <?php endif; ?>
            <?php if ($r['cn_friendly']>0): ?>
              <span class="cn" title="China-accessibility">CN <?= str_repeat('★', (int)$r['cn_friendly']) ?></span>
            <?php endif; ?>
          </div>
          <a class="cta" href="/en/listing/<?= (int)$r['id'] ?>">View details →</a>
        </div>
      </div>
    <?php endforeach; ?>
  </div>

  <h2 class="section-h">🆕 Recently added</h2>
  <p class="section-sub">Latest provider entries — directory refreshed daily.</p>
  <div class="recent-list">
    <?php foreach ($recent as $r):
        $cat_lbl = $CATS[$r['category']][0] ?? $r['category'];
    ?>
      <div class="item">
        <div>
          <a href="/en/listing/<?= (int)$r['id'] ?>"><?= h($r['provider']) ?></a>
          <span class="meta">· <?= h($cat_lbl) ?><?php if ($r['sub_category']): ?> / <?= h(tsub($r['sub_category'])) ?><?php endif; ?></span>
        </div>
        <div class="right">
          <?php if ($r['rating_avg']>0): ?>★ <?= number_format((float)$r['rating_avg'], 1) ?> · <?php endif; ?>
          <?php if ($r['price_monthly_usd']>0): ?>$<?= number_format((float)$r['price_monthly_usd'], 2) ?>/mo<?php endif; ?>
        </div>
      </div>
    <?php endforeach; ?>
  </div>

</div>

<footer>
  <div class="links">
    <a href="/en/listings">Directory</a> ·
    <a href="/en/sitemap.xml">Sitemap</a> ·
    <a href="/" hreflang="zh-CN">中文版</a> ·
    <a href="mailto:tg4g@duck.com">Feedback</a>
  </div>
  © TG4G Overseas Directory · Data compiled from public sources · Prices subject to vendor sites · Some links are affiliate (rel="sponsored")
</footer>

</body>
</html>
