<?php
/**
 * TG4G English homepage (/en/ and /en/index.php) — REDESIGN v2
 *
 * - Hero positioned for overseas SaaS / VPS / Payment audiences
 * - "China Accessibility Rating" + live vendor / review 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="zh-Hans" href="<?= h($zh_alt) ?>">
<link rel="alternate" hreflang="en"    href="<?= h($canonical) ?>">
<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/og-site.png">
<meta property="og:site_name" content="TG4G Overseas Resource Reviews">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://tg4g.com/og-site.png">
<meta name="robots" content="index,follow,max-image-preview:large">
<meta name="theme-color" content="#191814">
<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>
<link rel="stylesheet" href="/assets/redesign/redesign.css?v=<?= @filemtime($_SERVER['DOCUMENT_ROOT'].'/assets/redesign/redesign.css') ?: 1 ?>">
<style>
/* Production supplement: home-specific layout built on redesign.css tokens */
.lp-hero{margin-bottom:24px}
.lp-hero .eyebrow{font-size:12px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:var(--accent)}
.lp-hero h1{font-family:var(--font-display);font-size:34px;line-height:1.12;font-weight:700;letter-spacing:-.03em;margin:8px 0 12px;max-width:18ch}
.lp-hero h1 .accent{color:var(--accent-ink)}
.lp-hero .lp-sub{font-size:15px;color:var(--ink-2);max-width:62ch;margin:0 0 18px;line-height:1.6}
.lp-stats{display:flex;flex-wrap:wrap;gap:10px;margin-bottom:18px}
.lp-ctas{display:flex;flex-wrap:wrap;gap:10px}
.lp-ctas a{display:inline-flex;align-items:center;gap:6px;border-radius:9px;padding:11px 18px;font-size:13.5px;font-weight:700;text-decoration:none}
.lp-ctas a.primary{background:var(--accent);color:#fff}
.lp-ctas a.primary:hover{background:var(--accent-ink)}
.lp-ctas a.secondary{border:1px solid var(--line);background:var(--surface);color:var(--ink-2)}
.lp-ctas a.secondary:hover{border-color:var(--accent-line);color:var(--accent)}
.sec-head{display:flex;align-items:baseline;gap:10px;margin:28px 0 4px}
.sec-head h2{font-family:var(--font-display);font-size:22px;font-weight:700;letter-spacing:-.02em;margin:0}
.sec-head .count{font-size:13px;color:var(--accent);font-weight:600;font-family:var(--font-mono)}
.sec-sub{color:var(--ink-3);font-size:13px;margin:0 0 16px}
.cat-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:12px;margin-bottom:14px}
.cat-card{display:block;background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:16px 15px;text-decoration:none;transition:border-color .12s,transform .12s}
.cat-card:hover{border-color:var(--accent-line);transform:translateY(-2px)}
.cat-card .ic{font-size:24px;line-height:1}
.cat-card .nm{font-family:var(--font-display);font-weight:700;font-size:15px;color:var(--ink);margin-top:9px}
.cat-card .desc{font-size:11.5px;color:var(--ink-3);margin-top:3px;line-height:1.4;min-height:32px}
.cat-card .cnt{font-size:11px;color:var(--accent);font-weight:600;font-family:var(--font-mono);margin-top:7px}
.prov-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:12px;margin-bottom:14px}
.prov-card{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:16px;display:flex;flex-direction:column;justify-content:space-between;min-height:160px}
.prov-card .pc-top{display:flex;justify-content:space-between;align-items:flex-start;gap:8px}
.prov-card .pc-nm{font-family:var(--font-display);font-size:16px;font-weight:700;color:var(--ink);text-decoration:none}
.prov-card .pc-nm:hover{color:var(--accent)}
.prov-card .pc-rate{font-family:var(--font-mono);font-size:13px;color:var(--star);font-weight:700;white-space:nowrap}
.prov-card .pc-meta{color:var(--ink-3);font-size:11.5px;margin-top:8px;line-height:1.6}
.prov-card .pc-row{display:flex;justify-content:space-between;align-items:center;margin-top:12px;font-size:11.5px}
.prov-card .pc-price{color:var(--positive);font-weight:700;font-size:14px;font-family:var(--font-mono)}
.prov-card .pc-cn{color:var(--cn);font-weight:700;letter-spacing:-1px}
.prov-card .pc-cta{display:inline-flex;align-items:center;justify-content:center;margin-top:11px;background:var(--accent);color:#fff;padding:8px 12px;border-radius:8px;font-size:12.5px;font-weight:600;text-decoration:none}
.prov-card .pc-cta:hover{background:var(--accent-ink)}
.feat-list{padding:0;margin:0;list-style:none;display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px 26px}
.feat-list li{padding-left:24px;position:relative;font-size:13px;color:var(--ink-2);line-height:1.55}
.feat-list li::before{content:"✓";position:absolute;left:0;top:0;color:var(--positive);font-weight:900}
.feat-list li b{color:var(--ink)}
.recent{padding:0;border:1px solid var(--line);border-radius:var(--radius);overflow:hidden;background:var(--surface)}
.recent .row{display:flex;justify-content:space-between;align-items:center;padding:11px 16px;border-bottom:1px solid var(--line)}
.recent .row:last-child{border-bottom:0}
.recent a{color:var(--ink);font-weight:600;font-size:13px;text-decoration:none}
.recent a:hover{color:var(--accent)}
.recent .rc-meta{color:var(--ink-3);font-size:11.5px}
.recent .rc-right{color:var(--positive);font-weight:700;font-size:13px;font-family:var(--font-mono)}
@media(max-width:640px){.lp-hero h1{font-size:26px}.sec-head h2{font-size:19px}}
</style>
</head>
<body>
<?php
function hicon($n){
  $p='width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"';
  switch($n){
    case 'search': return "<svg $p><circle cx='11' cy='11' r='7'/><path d='m21 21-4.3-4.3'/></svg>";
    case 'bolt':   return "<svg $p><path d='M13 2 4 14h7l-1 8 9-12h-7z'/></svg>";
    case 'arrow':  return "<svg $p><path d='M5 12h14M13 6l6 6-6 6'/></svg>";
  }
  return '';
}
?>
<div class="app">
  <header class="site-head">
    <div class="util-bar"><div class="util-inner">
      <span class="upd"><span class="dot"></span>Updated <?= h(rel_time_en($dataset_updated)) ?></span>
      <nav class="meta-nav">
        <a class="meta-link" href="/best-2026">Rankings</a>
        <a class="meta-link" href="/compare">Compare</a>
        <a class="meta-link" href="/vps_engine.php">Config Engine</a>
        <a class="meta-link" href="/methodology">Methodology</a>
        <a class="meta-link" href="/about">About</a>
        <span class="lang-toggle"><button type="button" onclick="location.href='<?= h($zh_alt) ?>'">中</button><button class="on" type="button">EN</button></span>
      </nav>
    </div></div>
    <div class="head-inner">
      <a class="brand" href="/en/"><span class="brand-mark">tg4g</span><span class="brand-sub">Overseas Resource Reviews</span></a>
      <form class="head-search" method="get" action="/en/listings" role="search">
        <button class="sicon" type="submit" aria-label="Search"><?= hicon('search') ?></button>
        <input name="q" placeholder="Search providers, types, keywords…" aria-label="Search">
        <kbd>↵</kbd>
      </form>
    </div>
  </header>

  <nav class="cat-nav"><div class="cat-nav-inner">
    <?php foreach ($CATS as $k => [$lbl, $ic, $d]):
      $cnt = $cat_counts[$k] ?? 0; ?>
      <a class="cat-pill" href="/en/listings?cat=<?= h($k) ?>"><span><?= h($lbl) ?></span><em><?= number_format((int)$cnt) ?></em></a>
    <?php endforeach; ?>
  </div></nav>

  <div class="page">

    <section class="lp-hero">
      <div class="eyebrow">Overseas Resource Reviews</div>
      <h1><?= h(t('hero_title_en')) ?></h1>
      <p class="lp-sub"><?= h(t('hero_subtitle_en')) ?></p>
      <div class="lp-stats">
        <div class="stat"><b><?= number_format($total_all) ?></b><span>Vendors tracked</span></div>
        <div class="stat"><b><?= number_format($total_reviews) ?>+</b><span>In-depth reviews</span></div>
        <div class="stat"><b><?= count($CATS) ?></b><span>Categories</span></div>
        <div class="stat"><b>★★★</b><span>China-access rating</span></div>
      </div>
      <div class="lp-ctas">
        <a class="primary" href="/en/listings"><?= h(t('cta_browse_all')) ?> <?= hicon('arrow') ?></a>
        <a class="secondary" href="/en/listings?cat=vps">Top VPS providers</a>
        <a class="secondary" href="/en/listings?cat=payment">Payment &amp; virtual cards</a>
      </div>
    </section>

    <div class="sec-head"><h2><?= h(t('browse_by_category')) ?></h2><span class="count"><?= count($CATS) ?> categories</span></div>
    <p class="sec-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>

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

    <div class="sec-head"><h2><?= h(t('featured_top')) ?></h2><span class="count">rating ≥ 7.0</span></div>
    <p class="sec-sub">Top-rated overseas providers across all <?= count($CATS) ?> 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'];
        $durl = '/en/listing/' . (int)$r['id'];
      ?>
        <div class="prov-card">
          <div>
            <div class="pc-top">
              <a class="pc-nm" href="<?= $durl ?>"><?= h($r['provider']) ?></a>
              <span class="pc-rate">★ <?= number_format((float)$r['rating_avg'], 1) ?></span>
            </div>
            <div class="pc-meta">
              <span class="badge sub"><?= h($cat_lbl) ?></span>
              <?php if ($r['sub_category']): ?><span class="badge sub"><?= h(tsub($r['sub_category'])) ?></span><?php endif; ?>
              <?php if ($r['badge']): ?><span class="badge cn"><?= h($r['badge']) ?></span><?php endif; ?>
              <?php if ($r['plan_name']): ?><div style="margin-top:6px"><?= h($r['plan_name']) ?></div><?php endif; ?>
              <?php if ($r['hq_country']): ?><div style="margin-top:3px">HQ: <?= h($r['hq_country']) ?></div><?php endif; ?>
            </div>
          </div>
          <div>
            <div class="pc-row">
              <?php if ($r['price_monthly_usd']>0): ?><span class="pc-price">$<?= number_format((float)$r['price_monthly_usd'], 2) ?> / mo</span><?php else: ?><span style="color:var(--ink-3)">Pricing varies</span><?php endif; ?>
              <?php if ($r['cn_friendly']>0): ?><span class="pc-cn" title="China-accessibility">CN <?= str_repeat('★', (int)$r['cn_friendly']) ?></span><?php endif; ?>
            </div>
            <a class="pc-cta" href="<?= $durl ?>">View details →</a>
          </div>
        </div>
      <?php endforeach; ?>
    </div>

    <div class="sec-head"><h2>Recently added</h2></div>
    <p class="sec-sub">Latest provider entries — directory refreshed daily.</p>
    <div class="recent">
      <?php foreach ($recent as $r):
        $cat_lbl = $CATS[$r['category']][0] ?? $r['category']; ?>
        <div class="row">
          <div>
            <a href="/en/listing/<?= (int)$r['id'] ?>"><?= h($r['provider']) ?></a>
            <span class="rc-meta">· <?= h($cat_lbl) ?><?php if ($r['sub_category']): ?> / <?= h(tsub($r['sub_category'])) ?><?php endif; ?></span>
          </div>
          <div class="rc-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 class="site-foot">
    <div class="foot-links">
      <a class="meta-link" style="color:var(--ink-2)" href="/en/listings">Directory</a>
      <a class="meta-link" style="color:var(--ink-2)" href="/about">About</a>
      <a class="meta-link" style="color:var(--ink-2)" href="/methodology">Methodology</a>
      <a class="meta-link" style="color:var(--ink-2)" href="/best-2026">Rankings</a>
      <a class="meta-link" style="color:var(--ink-2)" href="<?= h($zh_alt) ?>" hreflang="zh-Hans">中文版</a>
    </div>
    <div>© tg4g · Data compiled from public sources · Prices subject to vendor sites · Some links are affiliate (rel=sponsored)</div>
  </footer>
</div>
</body>
</html>
