<?php
// 工厂页 - 两种模式：列表页 + 类别详细页
require_once __DIR__ . '/factory_config.php';

// 多语言检测：从URL参数 / 目录 / cookie读取
$allowed_langs = ['en', 'zh-CN', 'de-DE', 'ja', 'ar', 'pt-PT', 'ca-ES', 'fr-FR', 'hi-IN', 'ru-RU', 'vi', 'el', 'ko-KR', 'es'];
$rtl_langs = ['ar'];

$lang = $_GET['lang'] ?? ($_COOKIE['lang'] ?? 'en');
if (!in_array($lang, $allowed_langs)) $lang = 'en';
$is_rtl = in_array($lang, $rtl_langs);

// 语言映射表（URL短码→数据库代码）
$lang_map = [
    'ar' => 'ar', 'de' => 'de-DE', 'es' => 'es', 'fr' => 'fr-FR',
    'ru' => 'ru-RU', 'vi' => 'vi', 'pt' => 'pt-PT', 'ja' => 'ja',
    'ko' => 'ko-KR', 'ca' => 'ca-ES', 'hi' => 'hi-IN', 'el' => 'el',
    'zh' => 'zh-CN'
];
$lang_code = $lang_map[$lang] ?? $lang;

$catId = isset($_GET['id']) ? $_GET['id'] : '';
$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$view = ($_GET['view'] ?? '') === 'fac' ? 'fac' : 'cat';
$fcat = trim((string)($_GET['cat'] ?? ''));
$fcountry = trim((string)($_GET['country'] ?? 'CN'));

try {
    $pdo = db();

    /* ===== 工厂列表模式：直接读 fc_sup（与地图选厂同源） ===== */
    $facts = []; $facTotal = 0; $facPages = 1; $facCats = []; $facCountries = [];
    if ($view === 'fac') {
        $per = 24;
        $pgf = max(1, (int)($_GET['page'] ?? 1));
        $w = ["lat IS NOT NULL", "lng IS NOT NULL"];
        $args = [];
        if ($fcat !== '') { $w[] = "(cat1 = ? OR cat_zh = ?)"; $args[] = $fcat; $args[] = $fcat; }
        if ($fcountry !== '') { $w[] = "country = ?"; $args[] = $fcountry; }
        if ($q !== '') { $w[] = "name LIKE ?"; $args[] = '%'.$q.'%'; }
        $wsql = implode(' AND ', $w);
        $cst = $pdo->prepare("SELECT COUNT(*) FROM fc_sup WHERE $wsql"); $cst->execute($args);
        $facTotal = (int)$cst->fetchColumn();
        $facPages = max(1, (int)ceil($facTotal / $per));
        if ($pgf > $facPages) $pgf = $facPages;
        $off = ($pgf - 1) * $per;
        $lst = $pdo->prepare("SELECT id,name,logo_url,cat1,cat_zh,cat_en,city_cn,city,country,cluster,verified FROM fc_sup WHERE $wsql ORDER BY area_num DESC, id DESC LIMIT $per OFFSET $off");
        $lst->execute($args); $facts = $lst->fetchAll();
        foreach ($pdo->query("SELECT cat1 c, COUNT(*) n FROM fc_sup WHERE cat1<>'' GROUP BY cat1 ORDER BY n DESC LIMIT 60") as $r) { $facCats[] = $r; }
        foreach ($pdo->query("SELECT country c, COUNT(*) n FROM fc_sup WHERE country<>'' GROUP BY country ORDER BY n DESC LIMIT 40") as $r) { $facCountries[] = $r; }
    }
    
    // 类别详细页：支持数字id或类别名称slug
    $currentCat = null;
    if ($catId !== '') {
        // 如果是数字，按id查
        if (is_numeric($catId)) {
            $catStmt = $pdo->prepare("SELECT c.*, m.name as name_local, m.description as desc_local FROM fc_cat c LEFT JOIN fc_meta m ON c.id = m.cat_id AND m.lang = ? WHERE c.id = ? AND c.status = 1");
            $catStmt->execute([$lang_code, intval($catId)]);
            $currentCat = $catStmt->fetch(PDO::FETCH_ASSOC);
        }
        // 如果不是数字，先按slug查，查不到再按name_en查
        else {
            $catStmt = $pdo->prepare("SELECT * FROM fc_cat WHERE slug = ? AND status = 1");
            $catStmt->execute([$catId]);
            $currentCat = $catStmt->fetch(PDO::FETCH_ASSOC);
            // slug查不到，用name_en查（不区分大小写）
            if (!$currentCat) {
                $catStmt = $pdo->prepare("SELECT * FROM fc_cat WHERE LOWER(name_en) = LOWER(?) AND status = 1");
                $catStmt->execute([$catId]);
                $currentCat = $catStmt->fetch(PDO::FETCH_ASSOC);
            }
        }
    }
    
    if (!empty($currentCat)) {
        $catId = $currentCat['id'];
        
        // 查该类别下的产品（每页24个：4行x6列）
        $prodPage = isset($_GET['prod_page']) ? max(1, intval($_GET['prod_page'])) : 1;
        $prodPerPage = 24;
        $prodOffset = ($prodPage - 1) * $prodPerPage;
        
        $prodStmt = $pdo->prepare("
            SELECT * FROM fc_prod 
            WHERE status = 1 
            AND cat_id IN (SELECT id FROM fc_cat WHERE id = ? OR parent_id = ?) 
            ORDER BY id DESC 
            LIMIT $prodPerPage OFFSET $prodOffset
        ");
        $prodStmt->execute([$catId, $catId]);
        $products = $prodStmt->fetchAll(PDO::FETCH_ASSOC);
        
        $totalProds = $pdo->query("SELECT COUNT(*) FROM fc_prod WHERE status=1")->fetchColumn() ?: 760000;
    } else {
        // 列表页 → 默认显示顶级类别，搜索时搜所有类别
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $perPage = 50;
        $offset = ($page - 1) * $perPage;
        
        if ($q) {
            // 搜索时搜所有类别（包括二级、三级...）
            $searchType = 'categories';
            $countStmt = $pdo->prepare("SELECT COUNT(*) FROM fc_cat c WHERE c.status = 1 AND (c.name_en LIKE ? OR c.name_zh LIKE ?)");
            $countStmt->execute(["%$q%", "%$q%"]);
            $totalItems = $countStmt->fetchColumn();
            
            $stmt = $pdo->prepare("
                SELECT c.*, 
                  (SELECT p2.image FROM fc_prod p2 WHERE p2.cat_id = c.id AND p2.status = 1 ORDER BY p2.id DESC LIMIT 1) as cat_image,
                  (SELECT COUNT(*) FROM fc_prod p3 WHERE p3.cat_id = c.id AND p3.status = 1) as prod_count
                FROM fc_cat c 
                WHERE c.status = 1 
                AND (c.name_en LIKE ? OR c.name_zh LIKE ?)
                ORDER BY (SELECT COUNT(*) FROM fc_prod p3 WHERE p3.cat_id = c.id AND p3.status = 1) DESC, c.sort_order
                LIMIT $perPage OFFSET $offset
            ");
            $stmt->execute(["%$q%", "%$q%"]);
            $cats = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } else {
            // 默认显示顶级类别（大类别）
            $searchType = 'categories';
            $totalItems = $pdo->query("SELECT COUNT(*) FROM fc_cat WHERE status = 1")->fetchColumn();
            
            $stmt = $pdo->query("
                SELECT c.*, 
                  (SELECT p2.image FROM fc_prod p2 WHERE p2.cat_id = c.id AND p2.status = 1 ORDER BY p2.id DESC LIMIT 1) as cat_image,
                  (SELECT COUNT(*) FROM fc_prod p3 WHERE p3.cat_id = c.id AND p3.status = 1) as prod_count
                FROM fc_cat c 
                WHERE c.status = 1 
                ORDER BY (SELECT COUNT(*) FROM fc_prod p3 WHERE p3.cat_id = c.id AND p3.status = 1) DESC, c.sort_order
                LIMIT $perPage OFFSET $offset
            ");
            $cats = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        $totalPages = ceil($totalItems / $perPage);
        $totalProds = $pdo->query("SELECT COUNT(*) FROM fc_prod WHERE status=1")->fetchColumn();
    }
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
    exit;
}
?>
<!DOCTYPE html>
<html lang="<?php echo $lang; ?>" dir="<?php echo $is_rtl ? 'rtl' : 'ltr'; ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $catId ? htmlspecialchars($currentCat['name_en']) . ' - Factory Directory' : 'Factory Directory - shopeg.cn'; ?></title>
<link rel="stylesheet" href="https://miaoda.feishu.cn/fonts/css2?family=Inter:wght@400;500;600;700;800&display=swap">
<style>
*{margin:0;padding:0;box-sizing:border-box}
:root{
  --navy:#092143;--gold:#F4A51C;--gold-dark:#DE961A;
  --bg:#F8FAFC;--white:#fff;--text:#1A2736;--text-2:#52617A;--text-3:#94A3B8;--border:#E2E8F0;
}
body{font-family:'Inter',-apple-system,sans-serif;color:var(--text);background:var(--white);line-height:1.6}
img{max-width:100%;display:block}
a{text-decoration:none;color:inherit}
.container{max-width:1280px;margin:0 auto;padding:0 24px}

/* 导航 - 和首页统一 */
.nav{background:var(--navy);padding:16px 0;position:sticky;top:0;z-index:100}
.nav .wrap{display:flex;align-items:center;justify-content:space-between;gap:24px;max-width:1280px;margin:0 auto;padding:0 24px}
.nav .nav-links{display:flex;align-items:center;gap:24px;margin-left:auto}
.nav a{color:#C8D6E5;font-size:14px;font-weight:500;transition:color .2s;text-decoration:none}
.nav a:hover{color:#fff}
.nav .logo{font-size:22px;font-weight:800;color:#fff;letter-spacing:-.5px}
.nav .logo span{color:var(--gold)}

<?php if ($catId): ?>
/* ===== 类别详细页样式（vrso模板一模一样） ===== */
.hero{position:relative;height:480px;overflow:hidden;display:flex;align-items:center;background:linear-gradient(158deg,#0b2140 0%,#092143 44%,#05122a 100%)}
.hero .container{position:relative;z-index:2}
.hero-text{max-width:620px;padding:60px 0}
.hero h1{color:#fff;font-size:44px;line-height:1.15;font-weight:800;margin-bottom:16px;letter-spacing:-.5px}
.hero p{color:#B8C9DD;font-size:17px;margin-bottom:32px;line-height:1.6}
.hero-btns{display:flex;gap:14px;flex-wrap:wrap}
.btn-blue{background:#2563EB;color:#fff;padding:14px 30px;border-radius:6px;font-weight:600;font-size:15px;border:none;cursor:pointer;transition:all .2s;font-family:inherit}
.btn-blue:hover{background:#1D4ED8}
.btn-dark{background:rgba(0,0,0,.4);color:#fff;padding:14px 30px;border-radius:6px;font-weight:600;font-size:15px;border:1px solid rgba(255,255,255,.2);cursor:pointer;transition:all .2s;font-family:inherit}

/* 特色卡片（和vrso一模一样） */
.feat-cards{position:relative;z-index:5;margin-top:-60px}
.feat-cards-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:24px}
.fc{background:var(--navy);border-radius:10px;padding:28px;display:flex;gap:16px;align-items:flex-start;box-shadow:0 10px 40px rgba(15,43,70,.2)}
.fc-icon{width:44px;height:44px;background:rgba(255,255,255,.08);border-radius:8px;display:flex;align-items:center;justify-content:center;flex-shrink:0}
.fc-icon svg{width:22px;height:var(--gold)}
.fc h4{color:#fff;font-size:16px;font-weight:700;margin-bottom:4px}
.fc p{color:#8FA8C4;font-size:13px;line-height:1.5}

/* 统计 */
.stats-sec{background:var(--white);padding:60px 0 40px}
.stats-row{display:grid;grid-template-columns:repeat(3,1fr);gap:0;max-width:800px;margin:0 auto}
.stat{text-align:center;padding:20px;border-right:1px solid var(--border)}
.stat:last-child{border-right:none}
.stat-num{font-size:32px;font-weight:800;color:var(--navy)}
.stat-num small{font-size:14px;color:var(--gold)}
.stat-label{font-size:13px;color:var(--text-2);margin-top:4px}

/* 面包屑 */
.breadcrumb{padding:20px 0;font-size:14px;color:var(--text-2)}
.breadcrumb a{color:var(--gold-dark);text-decoration:none}
.breadcrumb span{margin:0 8px}

/* 产品网格 */
.section{padding:60px 0}
.section-head{text-align:center;margin-bottom:40px}
.section-tag{color:var(--gold-dark);font-size:12px;font-weight:600;letter-spacing:2px;text-transform:uppercase;margin-bottom:8px}
.section-title{font-size:32px;font-weight:700;color:var(--navy)}
.prod-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:20px}
.p-card{background:#fff;border-radius:10px;overflow:hidden;border:1px solid var(--border);transition:all .25s;cursor:pointer}
.p-card:hover{box-shadow:0 8px 24px rgba(15,43,70,.1);transform:translateY(-4px)}
.p-card img{width:100%;height:160px;object-fit:cover;background:#f1f1f1}
.p-body{padding:16px}
.p-body h4{font-size:14.5px;color:var(--navy);margin-bottom:4px;line-height:1.4;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.p-body p{font-size:13px;color:var(--gold-dark);font-weight:600}

<?php else: ?>
/* ===== 类别列表页样式 ===== */
.hero{background:linear-gradient(158deg,#0b2140 0%,#092143 44%,#05122a 100%);padding:60px 0;text-align:center}
.hero h1{color:#fff;font-size:42px;font-weight:800;margin-bottom:12px;letter-spacing:-.5px}
.hero p{color:#B8C9DD;font-size:16px;margin-bottom:32px}
.search-box{max-width:600px;margin:0 auto;display:flex;gap:0;background:#fff;border-radius:8px;overflow:hidden;box-shadow:0 4px 20px rgba(0,0,0,.15)}
.search-box input{flex:1;padding:16px 20px;border:none;font-size:15px;outline:none;font-family:inherit}
.search-box button{background:var(--gold);color:#fff;padding:16px 32px;border:none;font-size:15px;font-weight:600;cursor:pointer;font-family:inherit}

.stats{background:#fff;padding:40px 0;border-bottom:1px solid var(--border)}
.stats-row{display:grid;grid-template-columns:repeat(3,1fr);gap:20px;max-width:800px;margin:0 auto;text-align:center}
.stat-num{font-size:32px;font-weight:800;color:var(--navy)}
.stat-num small{font-size:14px;color:var(--gold)}
.stat-label{font-size:13px;color:var(--text-2);margin-top:4px}

.cats-section{padding:60px 0}
.cats-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:12px}
.cat-card{background:#fff;border-radius:12px;overflow:hidden;border:1px solid var(--border);transition:all .25s;cursor:pointer}
.cat-card:hover{box-shadow:0 12px 32px rgba(15,43,70,.12);transform:translateY(-4px)}
.cat-card img{width:100%;height:220px;object-fit:cover;background:#f1f1f1}
.cat-body{padding:20px}
.cat-body h3{font-size:16px;color:var(--navy);margin-bottom:6px;line-height:1.4}
.cat-body p{font-size:13px;color:var(--text-3)}
.cat-body .count{display:inline-block;background:rgba(212,168,83,.1);color:var(--gold-dark);padding:2px 10px;border-radius:20px;font-size:12px;font-weight:600;margin-top:8px}
<?php endif; ?>

/* 底栏 */
.footer{background:var(--navy);color:#8FA8C4;padding:60px 0 20px;margin-top:60px}
.footer-grid{display:grid;grid-template-columns:2fr 1fr 1fr;gap:40px;margin-bottom:40px}
.footer h4{color:#fff;font-size:16px;margin-bottom:16px}
.footer p{font-size:14px;line-height:1.8;margin-bottom:8px}
.footer a{color:#8FA8C4;text-decoration:none;font-size:14px;display:block;margin-bottom:8px}
.footer a:hover{color:#fff}
.footer-bottom{border-top:1px solid rgba(255,255,255,.1);padding-top:20px;text-align:center;font-size:13px}

@media (max-width:768px){
  .prod-grid,.cats-grid,.feat-cards-grid{grid-template-columns:repeat(2,1fr)}
  .stats-row{grid-template-columns:repeat(3,1fr) !important;gap:4px !important}
  .stat-num{font-size:19px !important}
  .stat-label{font-size:11px !important}
  .stats{padding:18px 0 !important}
  .footer-grid{grid-template-columns:1fr}
  .nav .wrap{flex-wrap:wrap;gap:12px}
  .nav-links{flex-wrap:wrap;gap:8px;font-size:13px}
  .hero h1{font-size:28px}
  .hero{height:auto;padding:40px 0}
  .about-grid{grid-template-columns:1fr!important;gap:20px}
  .container{padding:0 16px}
  .feat-cards{margin-top:-30px}
}

/* 询盘表单弹窗 */
.modal-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:999;display:none;align-items:center;justify-content:center;padding:20px}
.modal-overlay.active{display:flex}
.modal{background:#fff;border-radius:12px;width:100%;max-width:500px;max-height:90vh;overflow-y:auto}
.modal-header{display:flex;justify-content:space-between;align-items:center;padding:20px 24px;border-bottom:1px solid #eee}
.modal-header h3{font-size:20px;color:#1a3a6b}
.modal-close{background:none;border:none;font-size:24px;cursor:pointer;color:#999}
.modal-body{padding:24px}
.form-group{margin-bottom:16px}
.form-group label{display:block;font-size:14px;color:#333;margin-bottom:6px;font-weight:500}
.form-group input,.form-group textarea{width:100%;padding:10px 12px;border:1px solid #ddd;border-radius:6px;font-size:14px;font-family:inherit;box-sizing:border-box}
.form-group textarea{min-height:100px;resize:vertical}
.btn-submit{width:100%;padding:14px;background:#1a3a6b;color:#fff;border:none;border-radius:6px;font-size:15px;font-weight:600;cursor:pointer}
.btn-submit:hover{background:#2c5aa0}
</style>

<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-NXBZYJ7MLF"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-NXBZYJ7MLF');
</script>

<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/6a4500040d47331d47d88684/1jseog4j6';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->

<link rel="canonical" href="https://shopeg.cn/factory_page.php">
</head>
<body>

<?php require_once __DIR__ . '/_site_chrome.php'; site_head(); ?>

<?php if ($catId): ?>
<!-- ===== 类别详细页 ===== -->
<section class="hero">
  <div class="container">
    <div class="hero-text">
      <h1><?= htmlspecialchars($currentCat['name_en']); ?><br>Factory</h1>
      <p>Welcome your inquiry for wholesale cooperation, we reply within working hours.</p>
      <div class="hero-btns">
        <button class="btn-blue" onclick="document.getElementById('products').scrollIntoView()">Browse Products</button>
        <button class="btn-dark" onclick="window.open('https://wa.me/8618801454718','_blank')">Contact Us</button>
      </div>
    </div>
  </div>
</section>

<!-- 面包屑（类别路径） -->
<div class="container">
  <div class="breadcrumb">
    <a href="/factory_page.php">Factory Directory</a>
    <span>/</span>
    <b><?= htmlspecialchars($currentCat['name_en']); ?></b>
  </div>
</div>

<!-- 特色卡片（工厂实力） -->
<section class="feat-cards">
  <div class="container">
    <div class="feat-cards-grid">
      <div class="fc">
        <div class="fc-icon"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L2 7v10c0 5.55 3.84 9.74 9 11 5.16-1.26 9-5.45 9-11V7l-9-5z"/></svg></div>
        <div>
          <h4>Verified Factory</h4>
          <p>Direct source factory for industrial products.</p>
        </div>
      </div>
      <div class="fc">
        <div class="fc-icon"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M20 6h-4V4c0-1.1-.9-2-2-2h-4c-1.1 0-2 .9-2 2v2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-6-2h-4V4h4v0zm2 12H8v-2h8v2zm0-4H8v-2h8v2z"/></svg></div>
        <div>
          <h4>Factory-Direct Price</h4>
          <p>No middle-man markup, competitive wholesale price for bulk order.</p>
        </div>
      </div>
      <div class="fc">
        <div class="fc-icon"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg></div>
        <div>
          <h4>Fast Delivery</h4>
          <p>Ship worldwide by sea, air or express in 3-7 days.</p>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- 产品展示第一行（4个大图） -->
<section style="padding:40px 0;background:#fff">
  <div class="container">
    <div class="section-head">
      <h2 class="section-title">Featured Products</h2>
    </div>
    <div class="prod-grid">
      <?php foreach (array_slice($products, 0, 4) as $p): ?>
      <div class="p-card">
        <img src="<?= htmlspecialchars($p['image']); ?>" alt="<?= htmlspecialchars($p['title']); ?>" loading="lazy" onerror="this.style.background='#f1f1f1'">
        <div class="p-body">
          <h4><?= htmlspecialchars($p['title']); ?></h4>
          <p><?= htmlspecialchars('Price on request'); ?></p>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>

<!-- 工厂展示（关于我们 + 图片） -->
<section style="padding:60px 0;background:#f8f9fa">
  <div class="container">
    <div class="about-grid" style="display:grid;grid-template-columns:1fr 1fr;gap:40px;align-items:center">
      <div>
        <div style="font-size:14px;color:var(--gold-dark);font-weight:600;margin-bottom:12px">ABOUT US</div>
        <h2 style="font-size:32px;color:var(--navy);margin-bottom:16px;line-height:1.3">Professional <?= htmlspecialchars($currentCat['name_en']); ?> Manufacturer</h2>
        <p style="color:var(--text-2);font-size:15px;line-height:1.7;margin-bottom:16px">We are a verified factory with 10+ years experience in <?= htmlspecialchars($currentCat['name_en']); ?> industry. Our products are exported to 50+ countries worldwide.</p>
        <p style="color:var(--text-2);font-size:15px;line-height:1.7">We offer OEM & ODM services, custom packaging, and competitive wholesale pricing.</p>
      </div>
      <div>
        <img src="/assets/factory_interior.jpg" alt="Factory Interior" style="width:100%;border-radius:12px;box-shadow:0 10px 40px rgba(15,43,70,.15)">
      </div>
    </div>
  </div>
</section>

<!-- 统计 -->
<section class="stats-sec">
  <div class="container">
    <div class="stats-row">
      <div class="stat">
        <div class="stat-num"><?= number_format(count($products)); ?></div>
        <div class="stat-label">Products</div>
      </div>
      <div class="stat">
        <div class="stat-num"><?= number_format($totalProds); ?><small>+</small></div>
        <div class="stat-label">Total Products</div>
      </div>
      <div class="stat">
        <div class="stat-num">24/7</div>
        <div class="stat-label">Support</div>
      </div>
    </div>
  </div>
</section>

<!-- 产品列表 -->
<section class="section" id="products">
  <div class="container">
    <div class="section-head">
      <div class="section-tag">Products</div>
      <h2 class="section-title"><?= count($products); ?> Products</h2>
    </div>
    <?php if (empty($products)): ?>
    <div style="text-align:center;padding:60px;color:#999;">No products found in this category.</div>
    <?php else: ?>
    <div class="prod-grid">
      <?php foreach (array_slice($products, 4) as $p): ?>
      <div class="p-card">
        <img src="<?= htmlspecialchars($p['image']); ?>" alt="<?= htmlspecialchars($p['title']); ?>" loading="lazy" onerror="this.style.background='#f1f1f1'">
        <div class="p-body">
          <h4><?= htmlspecialchars($p['title']); ?></h4>
          <p><?= htmlspecialchars('Price on request'); ?></p>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </div>
</section>

<?php else: ?>
<!-- ===== 类别列表页 ===== -->
<section class="hero">
  <div class="container">
    <h1>World Factory</h1>
    <p>Browse <?= number_format($totalItems); ?> product categories. Direct from verified factories.</p>
    <form class="search-box" method="get" action="/factory_page.php">
      <input type="text" name="q" placeholder="Search categories..." value="<?= htmlspecialchars($q); ?>">
      <button type="submit">Search</button>
    </form>
  </div>
</section>

<!-- 统计 -->
<section class="stats">
  <div class="container">
    <div class="stats-row">
      <div class="stat">
        <div class="stat-num"><?= number_format($totalItems); ?></div>
        <div class="stat-label">Categories</div>
      </div>
      <div class="stat">
        <div class="stat-num"><?= number_format($totalProds); ?></div>
        <div class="stat-label">Products</div>
      </div>
      <div class="stat">
        <div class="stat-num"><?= number_format($totalPages); ?></div>
        <div class="stat-label">Pages</div>
      </div>
    </div>
  </div>
</section>

<!-- 切换：类目 / 工厂 -->
<div class="container" style="margin:18px auto 0;display:flex;gap:8px;flex-wrap:wrap;align-items:center">
  <a href="/factory_page.php<?= $q?'?q='.urlencode($q):'' ?>" style="padding:7px 14px;border-radius:20px;font-size:13px;text-decoration:none;<?= $view==='cat'?'background:#0f2b46;color:#fff':'background:#fff;color:#0f2b46;border:1px solid #dbe3ee' ?>">Categories 类目 (<?= number_format((int)$totalItems) ?>)</a>
  <a href="/factory_page.php?view=fac<?= $q?'&q='.urlencode($q):'' ?>" style="padding:7px 14px;border-radius:20px;font-size:13px;text-decoration:none;<?= $view==='fac'?'background:#0f2b46;color:#fff':'background:#fff;color:#0f2b46;border:1px solid #dbe3ee' ?>">Factories 工厂 (<?= number_format(27081) ?>)</a>
</div>

<?php if ($view === 'fac'): ?>
<section class="cats-section">
  <div class="container">
    <form method="get" action="/factory_page.php" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-bottom:18px">
      <input type="hidden" name="view" value="fac">
      <input type="text" name="q" value="<?= htmlspecialchars($q) ?>" placeholder="Search factory name 搜索工厂名" style="height:36px;padding:0 12px;border:1px solid #dbe3ee;border-radius:8px;min-width:220px">
      <select name="cat" style="height:36px;padding:0 10px;border:1px solid #dbe3ee;border-radius:8px">
        <option value="">All categories 全部品类</option>
        <?php foreach ($facCats as $c): ?><option value="<?= htmlspecialchars($c['c']) ?>"<?= $fcat===$c['c']?' selected':'' ?>><?= htmlspecialchars($c['c']) ?> (<?= number_format((int)$c['n']) ?>)</option><?php endforeach; ?>
      </select>
      <select name="country" style="height:36px;padding:0 10px;border:1px solid #dbe3ee;border-radius:8px">
        <option value="">All countries 全部国家</option>
        <?php foreach ($facCountries as $c): ?><option value="<?= htmlspecialchars($c['c']) ?>"<?= $fcountry===$c['c']?' selected':'' ?>><?= htmlspecialchars($c['c']) ?> (<?= number_format((int)$c['n']) ?>)</option><?php endforeach; ?>
      </select>
      <button type="submit" style="height:36px;padding:0 18px;border:0;border-radius:8px;background:#f0a500;color:#fff;font-weight:700;cursor:pointer">Search</button>
      <span style="margin-left:auto;color:#7b8797;font-size:12.5px"><?= number_format($facTotal) ?> factories · page <?= $pgf ?? 1 ?>/<?= $facPages ?></span>
    </form>
    <?php if (!$facts): ?>
      <div style="text-align:center;padding:50px;color:#8b95a5">No factory found. 换个条件试试。</div>
    <?php else: ?>
    <div class="cats-grid">
      <?php foreach ($facts as $f): ?>
      <a class="cat-card" href="/factory_profile.php?id=<?= (int)$f['id'] ?>" style="text-decoration:none">
        <img src="<?= htmlspecialchars($f['logo_url']) ?>" alt="<?= htmlspecialchars($f['name']) ?>" loading="lazy" style="object-fit:contain;background:#fff" onerror="this.style.display='none';this.parentNode.insertAdjacentHTML('afterbegin','<div style=&quot;height:160px;display:flex;align-items:center;justify-content:center;background:#eef3fb;color:#4a6da8;font-weight:800;font-size:20px&quot;>F</div>')">
        <div class="cat-body">
          <h3><?= htmlspecialchars($f['name']) ?></h3>
          <?php $isZh = strpos((string)$lang,'zh')===0; $fc1 = $isZh ? ($f['cat_zh'] ?: $f['cat1']) : ($f['cat_en'] ?: $f['cat1']); $fc2 = $isZh ? '' : ($f['cat_zh'] && $f['cat_zh'] !== $fc1 ? $f['cat_zh'] : ''); ?>
          <p><?= htmlspecialchars($fc1) ?><?= $fc2 ? ' · '.htmlspecialchars($fc2) : '' ?></p>
          <span class="count"><?= htmlspecialchars($isZh ? ($f['city_cn'] ?: $f['city']) : ($f['city'] ?: $f['city_cn'])) ?><?= (int)$f['verified']===1 ? ' · Verified' : '' ?></span>
        </div>
      </a>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
    <?php if ($facPages > 1): $base = '?view=fac'.($q?'&q='.urlencode($q):'').($fcat?'&cat='.urlencode($fcat):'').($fcountry?'&country='.urlencode($fcountry):''); ?>
    <div style="display:flex;justify-content:center;gap:8px;margin-top:32px;flex-wrap:wrap">
      <?php if (($pgf ?? 1) > 1): ?><a href="<?= $base ?>&page=<?= $pgf-1 ?>" style="padding:9px 15px;border:1px solid #dbe3ee;border-radius:6px;text-decoration:none;color:#0f2b46">← Prev</a><?php endif; ?>
      <?php for ($i = max(1, $pgf-2); $i <= min($facPages, $pgf+2); $i++): ?>
      <a href="<?= $base ?>&page=<?= $i ?>" style="padding:9px 14px;border-radius:6px;text-decoration:none;<?= $i === ($pgf ?? 1) ? 'background:#0f2b46;color:#fff' : 'border:1px solid #dbe3ee;color:#0f2b46' ?>"><?= $i ?></a>
      <?php endfor; ?>
      <?php if (($pgf ?? 1) < $facPages): ?><a href="<?= $base ?>&page=<?= $pgf+1 ?>" style="padding:9px 15px;border:1px solid #dbe3ee;border-radius:6px;text-decoration:none;color:#0f2b46">Next →</a><?php endif; ?>
    </div>
    <?php endif; ?>
  </div>
</section>
<?php else: ?>

<!-- 列表（类别或产品） -->
<section class="cats-section">
  <div class="container">
    <?php if ($searchType == 'products'): ?>
      <!-- 搜索结果：产品列表 -->
      <?php if (empty($products)): ?>
      <div style="text-align:center;padding:60px;color:#999;">No products found for "<?= htmlspecialchars($q); ?>". Try another keyword.</div>
      <?php else: ?>
      <div class="prod-grid">
        <?php foreach ($products as $p): ?>
        <div class="p-card" onclick="location.href='/#/p/<?= $p['id']; ?>'">
          <img src="<?= htmlspecialchars($p['image']); ?>" alt="<?= htmlspecialchars($p['title']); ?>" loading="lazy" onerror="this.style.background='#f1f1f1'">
          <div class="p-body">
            <h4><?= htmlspecialchars($p['title']); ?></h4>
            <p><?= htmlspecialchars('Price on request'); ?></p>
          </div>
        </div>
        <?php endforeach; ?>
        <?php
        // 最后一行补齐
        $missing = 5 - (count($cats) % 5);
        if ($missing < 5) {
          for ($i = 0; $i < $missing; $i++) {
            echo '<div class="cat-card" style="visibility:hidden"></div>';
          }
        }
        ?>
      </div>
      <?php endif; ?>
    <?php else: ?>
      <!-- 默认：类别列表 -->
      <?php if (empty($cats)): ?>
      <div style="text-align:center;padding:60px;color:#999;">No categories found. Try another search.</div>
      <?php else: ?>
      <div class="cats-grid">
        <?php foreach ($cats as $cat): ?>
        <div class="cat-card" onclick="location.href='/factory_page.php?id=<?= $cat['slug']; ?>'">
          <img src="<?= htmlspecialchars($cat['cat_image'] ?: $cat['image'] ?: '') ?>" alt="<?= htmlspecialchars($cat['name_en']) ?>" loading="lazy" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22400%22 height=%22160%22><rect fill=%22%23f1f1f1%22 width=%22400%22 height=%22160%22/></svg>'">
          <div class="cat-body">
            <h3><?= htmlspecialchars($cat['name_en']); ?></h3>
            <p><?= htmlspecialchars($cat['name_zh']); ?></p>
            <span class="count"><?= number_format($cat['prod_count']); ?> products</span>
          </div>
        </div>
        <?php endforeach; ?>
        <?php
        // 最后一行补齐
        $missing = 5 - (count($cats) % 5);
        if ($missing < 5) {
          for ($i = 0; $i < $missing; $i++) {
            echo '<div class="cat-card" style="visibility:hidden"></div>';
          }
        }
        ?>
      </div>
      <?php endif; ?>
    <?php endif; ?>
    
    <!-- 分页导航 -->
    <?php if ($totalPages > 1): ?>
    <div style="display:flex;justify-content:center;align-items:center;gap:8px;margin-top:40px;flex-wrap:wrap">
      <?php if ($page > 1): ?>
      <a href="?page=<?= $page-1; ?><?= $q ? '&q='.urlencode($q) : '' ?>" style="padding:10px 16px;background:#fff;border:1px solid var(--border);border-radius:6px;color:var(--navy);text-decoration:none;font-size:14px">← Previous</a>
      <?php endif; ?>
      
      <?php
      $start = max(1, $page - 2);
      $end = min($totalPages, $page + 2);
      for ($i = $start; $i <= $end; $i++):
      ?>
      <a href="?page=<?= $i; ?><?= $q ? '&q='.urlencode($q) : '' ?>" style="padding:10px 16px;border-radius:6px;font-size:14px;text-decoration:none;<?= $i == $page ? 'background:var(--gold);color:#fff;border:1px solid var(--gold);font-weight:600' : 'background:#fff;border:1px solid var(--border);color:var(--navy)'; ?>"><?= $i; ?></a>
      <?php endfor; ?>
      
      <?php if ($page < $totalPages): ?>
      <a href="?page=<?= $page+1; ?><?= $q ? '&q='.urlencode($q) : '' ?>" style="padding:10px 16px;background:#fff;border:1px solid var(--border);border-radius:6px;color:var(--navy);text-decoration:none;font-size:14px">Next →</a>
      <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <?php endif; ?>
  </div>
</section>
<?php endif; ?>

<!-- 底栏 -->

<!-- CONTACT 表单区块 - 只有详细页显示 -->
<?php if (!empty($currentCat)): ?>
<section style="padding:60px 0;background:#f8f9fa">
  <div class="container">
    <div style="max-width:800px;margin:0 auto">
      <div style="text-align:center;margin-bottom:40px">
        <h2 style="font-size:32px;color:#1a3a6b;margin-bottom:12px">Get In Touch</h2>
        <p style="color:#666;font-size:16px">Wholesale & OEM Inquiries Welcome</p>
      </div>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:40px">
        <div>
          <h3 style="font-size:18px;color:#333;margin-bottom:20px">Contact Info</h3>
          <p style="color:#666;margin-bottom:12px"><strong>Phone / WhatsApp:</strong> +86 188 0145 4718</p>
          <p style="color:#666;margin-bottom:12px"><strong>Email:</strong> vip@vgsz.cn</p>
          <p style="color:#666;margin-bottom:12px"><strong>Address:</strong> China Factory</p>
        </div>
        <div>
          <form id="inquiryForm" onsubmit="submitInquiry(event)">
            <div style="margin-bottom:16px">
              <input type="text" id="inqName" name="name" required placeholder="Name *" style="width:100%;padding:10px 12px;border:1px solid #ddd;border-radius:6px;font-size:14px">
            </div>
            <div style="margin-bottom:16px">
              <input type="text" id="inqCompany" name="company" placeholder="Company" style="width:100%;padding:10px 12px;border:1px solid #ddd;border-radius:6px;font-size:14px">
            </div>
            <div style="margin-bottom:16px">
              <input type="email" id="inqEmail" name="email" required placeholder="Email *" style="width:100%;padding:10px 12px;border:1px solid #ddd;border-radius:6px;font-size:14px">
            </div>
            <div style="margin-bottom:16px">
              <input type="text" id="inqCountry" name="country" placeholder="Country" style="width:100%;padding:10px 12px;border:1px solid #ddd;border-radius:6px;font-size:14px">
            </div>
            <div style="margin-bottom:16px">
              <textarea id="inqMessage" name="message" required placeholder="Message" style="width:100%;padding:10px 12px;border:1px solid #ddd;border-radius:6px;font-size:14px;min-height:100px;resize:vertical"></textarea>
            </div>
            <button type="submit" style="width:100%;padding:14px;background:#1a3a6b;color:#fff;border:none;border-radius:6px;font-size:15px;font-weight:600;cursor:pointer">Send Inquiry</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</section>
<?php endif; ?>


<!-- CONTACT 表单区块 - 只有详细页显示 -->
<?php if (!empty($currentCat)): ?>

<?php endif; ?>

<script>
function submitInquiry(e) {
  e.preventDefault();
  var form = document.getElementById('inquiryForm');
  var data = new FormData(form);
  
  // 自动记录页面信息
  data.append('site', 'shopeg.cn');
  data.append('page_title', document.title);
  data.append('page_url', window.location.href);
  <?php if (!empty($currentCat)): ?>
  data.append('product_id', '<?= $currentCat['id'] ?>');
  data.append('product_name', '<?= $currentCat['name_en'] ?>');
  <?php endif; ?>
  
  fetch('/submit_inquiry.php', {
    method: 'POST',
    body: data
  })
  .then(r => r.json())
  .then(res => {
    if (res.code === 1) {
      alert('Inquiry sent successfully! We will contact you within 24 hours.');
      form.reset();
    } else {
      alert('Error: ' + (res.msg || 'Failed to submit inquiry'));
    }
  })
  .catch(err => {
    alert('Error: ' + err.message);
  });
  
  return false;
}
</script>

<?php site_foot(); ?>

<script>

}
</script>


<!-- 语言切换器 -->
<div style="position:fixed;bottom:16px;left:16px;z-index:9999;background:#fff;padding:6px 8px;border-radius:8px;box-shadow:0 6px 18px rgba(9,33,67,.18);border:1px solid #e6ebf2">
    <select onchange="changeLang(this.value)" style="padding:6px;border:1px solid #ddd;border-radius:4px;cursor:pointer;">
        <option value="en" <?= $lang==='en'?'selected':'' ?>>English</option>
        <option value="zh-CN" <?= $lang==='zh-CN'?'selected':'' ?>>中文</option>
        <option value="de-DE" <?= $lang==='de-DE'?'selected':'' ?>>Deutsch</option>
        <option value="ja" <?= $lang==='ja'?'selected':'' ?>>日本語</option>
        <option value="ar" <?= $lang==='ar'?'selected':'' ?>>العربية</option>
        <option value="pt-PT" <?= $lang==='pt-PT'?'selected':'' ?>>Português</option>
        <option value="ca-ES" <?= $lang==='ca-ES'?'selected':'' ?>>Català</option>
        <option value="fr-FR" <?= $lang==='fr-FR'?'selected':'' ?>>Français</option>
        <option value="hi-IN" <?= $lang==='hi-IN'?'selected':'' ?>>हिन्दी</option>
        <option value="ru-RU" <?= $lang==='ru-RU'?'selected':'' ?>>Русский</option>
        <option value="vi" <?= $lang==='vi'?'selected':'' ?>>Tiếng Việt</option>
        <option value="el" <?= $lang==='el'?'selected':'' ?>>Ελληνικά</option>
        <option value="ko-KR" <?= $lang==='ko-KR'?'selected':'' ?>>한국어</option>
        <option value="es" <?= $lang==='es'?'selected':'' ?>>Español</option>
    </select>
</div>
<script>
function changeLang(lang) {
    var url = new URL(window.location.href);
    url.searchParams.set('lang', lang);
    window.location.href = url.toString();
}
</script>

</body>
</html>

