<?php
$pageTitle = 'Green Hat B2B — বাংলাদেশের পাইকারি মার্কেটপ্লেস';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/lang.php';

$db = getDB();
$featuredProducts = getProducts([], 8, 0);
$recentlyViewed   = isLoggedIn() ? getRecentlyViewed($_SESSION['user_id']) : [];
$categories       = getCategories();
require_once __DIR__ . '/includes/render-product-section.php';

// Load custom sections
$customSections = [];
try {
    $customSections = $db->query("
        SELECT * FROM homepage_sections
        WHERE `key` LIKE 'custom_%' AND is_enabled=1
        ORDER BY sort_order ASC, id ASC
    ")->fetchAll();
} catch (Exception $e) { $customSections = []; }

/* ── Load homepage section configs from DB ─────────────────────────── */
function sectionCfg(string $key, string $field, string $default = ''): string {
    static $cache = [];
    if (!isset($cache[$key])) {
        try {
            $st = getDB()->prepare("SELECT config FROM homepage_sections WHERE `key`=? AND is_enabled=1");
            $st->execute([$key]);
            $cache[$key] = json_decode($st->fetchColumn() ?: '{}', true) ?? [];
        } catch (Exception $e) { $cache[$key] = []; }
    }
    return htmlspecialchars($cache[$key][$field] ?? $default, ENT_QUOTES, 'UTF-8');
}

require_once __DIR__ . '/includes/header.php';
?>

<!-- ── Hero ─────────────────────────────────────────────────────────── -->
<?php
$_heroBgStart = sectionCfg('hero','bg_start','');
$_heroBgEnd   = sectionCfg('hero','bg_end','');
$_heroStyle   = ($_heroBgStart && $_heroBgEnd)
    ? ' style="background:linear-gradient(135deg,' . $_heroBgStart . ',' . $_heroBgEnd . ')"'
    : '';
?>
<section class="hero" data-section="hero"<?= $_heroStyle ?>>
  <div class="container">
    <div class="hero-inner">
      <div class="hero-content">
        <div class="hero-badge">
          <i class="bi bi-shield-check-fill"></i>
          <span data-ve="badge_text"><?= sectionCfg('hero','badge_text', '🇧🇩 ' . __('home.hero_title')) ?></span>
        </div>
        <h1 data-ve="heading"><?= sectionCfg('hero','heading', LANG==='bn' ? 'পাইকারি কিনুন,<br>সাশ্রয় করুন' : 'Buy Wholesale,<br>Save More') ?></h1>
        <p data-ve="subheading"><?= sectionCfg('hero','subheading', __('home.hero_sub')) ?></p>
        <div class="hero-actions">
          <a href="/Green_Hat_B2B/pages/products.php" class="btn btn-primary btn-lg">
            <i class="bi bi-bag-fill"></i> <span data-ve="cta1"><?= sectionCfg('hero','cta1_label', __('home.shop_now')) ?></span>
          </a>
          <a href="/Green_Hat_B2B/auth/register.php" class="btn btn-outline btn-lg" style="color:#fff;border-color:rgba(255,255,255,.5)">
            <i class="bi bi-person-plus"></i> <span data-ve="cta2"><?= sectionCfg('hero','cta2_label', __('home.become_vendor')) ?></span>
          </a>
        </div>
        <div class="hero-stats">
          <div class="hero-stat">
            <div class="num" data-ve="stat1_num"><?= sectionCfg('hero','stat1_num', LANG==='bn'?'২,৪০০+':'2,400+') ?></div>
            <div class="lbl" data-ve="stat1_lbl"><?= sectionCfg('hero','stat1_lbl', LANG==='bn'?'পণ্য':'Products') ?></div>
          </div>
          <div class="hero-stat">
            <div class="num" data-ve="stat2_num"><?= sectionCfg('hero','stat2_num', LANG==='bn'?'৮৫০+':'850+') ?></div>
            <div class="lbl" data-ve="stat2_lbl"><?= sectionCfg('hero','stat2_lbl', LANG==='bn'?'বিক্রেতা':'Vendors') ?></div>
          </div>
          <div class="hero-stat">
            <div class="num" data-ve="stat3_num"><?= sectionCfg('hero','stat3_num', LANG==='bn'?'১২K+':'12K+') ?></div>
            <div class="lbl" data-ve="stat3_lbl"><?= sectionCfg('hero','stat3_lbl', LANG==='bn'?'ক্রেতা':'Buyers') ?></div>
          </div>
          <div class="hero-stat">
            <div class="num" data-ve="stat4_num"><?= sectionCfg('hero','stat4_num', LANG==='bn'?'৯৯.২%':'99.2%') ?></div>
            <div class="lbl" data-ve="stat4_lbl"><?= sectionCfg('hero','stat4_lbl', LANG==='bn'?'সন্তুষ্টি':'Satisfaction') ?></div>
          </div>
        </div>
      </div>
      <div class="hero-visual">
        <div class="hero-cards">
          <?php
          $heroFeatures = [
            ['bi-truck-front-fill',LANG==='bn'?'দ্রুত ডেলিভারি':'Fast Delivery',    LANG==='bn'?'সারা বাংলাদেশে পৌঁছে দিই':'Delivery across Bangladesh'],
            ['bi-wallet2',         LANG==='bn'?'বিকাশ / নগদ':'bKash & Nagad',        LANG==='bn'?'মোবাইল ব্যাংকিং পেমেন্ট':'Mobile banking payments'],
            ['bi-chat-dots-fill',  LANG==='bn'?'লাইভ চ্যাট':'Live Chat',              LANG==='bn'?'সরাসরি বিক্রেতার সাথে':'Direct vendor negotiation'],
            ['bi-graph-up-arrow',  LANG==='bn'?'পরিমাণ ছাড়':'Volume Discounts',      LANG==='bn'?'বেশি কিনলে ৩০% সাশ্রয়':'Save up to 30% on bulk'],
          ];
          foreach ($heroFeatures as $f): ?>
            <div class="hero-card">
              <i class="bi <?= $f[0] ?>"></i>
              <h4><?= $f[1] ?></h4>
              <p><?= $f[2] ?></p>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- ── Category Bar ──────────────────────────────────────────────────── -->
<?php $_catBg = sectionCfg('categories','bg_color',''); ?>
<section class="page-section" data-section="categories"
  style="padding:36px 0 0<?= $_catBg ? ';background:' . $_catBg : '' ?>">
  <div class="container">
    <div class="section-header">
      <h2 class="section-title" data-ve="section_title">
        <?= sectionCfg('categories','section_title', __('home.categories')) ?>
      </h2>
      <a href="/Green_Hat_B2B/pages/products.php" class="view-all"><?= __('home.view_all') ?> <i class="bi bi-arrow-right"></i></a>
    </div>
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:14px;margin-bottom:40px">
      <?php foreach ($categories as $c): ?>
        <a href="/Green_Hat_B2B/pages/products.php?cat=<?= $c['id'] ?>"
           style="display:flex;flex-direction:column;align-items:center;gap:10px;padding:20px 12px;
                  background:#fff;border:1px solid var(--border);border-radius:var(--radius);
                  font-size:13px;font-weight:600;color:var(--dark);text-align:center;transition:all .2s;"
           onmouseover="this.style.borderColor='var(--primary)';this.style.color='var(--primary)';this.style.boxShadow='var(--shadow-md)'"
           onmouseout="this.style.borderColor='var(--border)';this.style.color='var(--dark)';this.style.boxShadow='none'">
          <span style="width:52px;height:52px;background:var(--primary-light);border-radius:50%;
                       display:grid;place-items:center;font-size:24px;color:var(--primary)">
            <i class="bi <?= e($c['icon']) ?>"></i>
          </span>
          <?= e($c['name']) ?>
        </a>
      <?php endforeach; ?>
    </div>
  </div>
</section>

<!-- ── Featured Products ─────────────────────────────────────────────── -->
<?php $_fpBg = sectionCfg('featured_products','bg_color',''); ?>
<section class="page-section" data-section="featured_products"
  style="padding-top:0<?= $_fpBg ? ';background:' . $_fpBg : '' ?>">
  <div class="container">
    <div class="section-header">
      <h2 class="section-title" data-ve="section_title">
        <?= sectionCfg('featured_products','section_title', __('home.featured')) ?>
      </h2>
      <a href="/Green_Hat_B2B/pages/products.php" class="view-all"><?= __('home.view_all') ?> <i class="bi bi-arrow-right"></i></a>
    </div>

    <?php if (!isLoggedIn() || !isApproved()): ?>
      <div class="alert alert-info" style="margin-bottom:20px">
        <i class="bi bi-info-circle-fill"></i>
        <div>
          <strong><?= __('product.price_locked') ?>.</strong>
          <a href="/Green_Hat_B2B/auth/register.php"><?= __('auth.register') ?></a>
          <?= LANG==='bn'?'বা':' or ' ?>
          <a href="/Green_Hat_B2B/auth/login.php"><?= __('auth.login') ?></a>
          <?= LANG==='bn'?'করুন এবং পাইকারি মূল্য দেখুন':'and get approved to view wholesale prices.' ?>
        </div>
      </div>
    <?php endif; ?>

    <div class="products-grid">
      <?php foreach ($featuredProducts as $p):
        $lowestTier = $db->prepare("SELECT MIN(price) FROM tiered_pricing WHERE product_id = ?");
        $lowestTier->execute([$p['id']]);
        $fromPrice = $lowestTier->fetchColumn();
      ?>
        <div class="product-card">
          <a href="/Green_Hat_B2B/pages/product-detail.php?slug=<?= e($p['slug']) ?>">
            <div class="product-card-img">
              <img src="<?= productImageUrl($p['image']) ?>" alt="<?= e($p['name']) ?>"
                   onerror="this.onerror=null;this.src='/Green_Hat_B2B/assets/images/placeholder.php'">
              <span class="product-card-badge badge-moq">MOQ <?= $p['min_order_qty'] ?></span>
            </div>
          </a>
          <div class="product-card-body">
            <div class="product-card-cat"><?= e($p['category_name']) ?></div>
            <a href="/Green_Hat_B2B/pages/product-detail.php?slug=<?= e($p['slug']) ?>">
              <div class="product-card-name"><?= e($p['name']) ?></div>
            </a>
            <div class="product-card-moq"><?= __('product.moq') ?>: <span><?= $p['min_order_qty'] ?> <?= __('lbl.units') ?></span></div>

            <?php if (isLoggedIn() && isApproved()): ?>
              <div class="product-price"><?= formatPrice((float)$p['base_price']) ?></div>
              <?php if ($fromPrice && $fromPrice < $p['base_price']): ?>
                <div class="product-price-from">
                  <?= LANG==='bn'?'থেকে শুরু':'From' ?> <?= formatPrice((float)$fromPrice) ?><?= __('lbl.per_unit') ?>
                  <?= LANG==='bn'?'বাল্কে':'on bulk' ?>
                </div>
              <?php endif; ?>
              <div class="product-card-actions">
                <button class="btn btn-outline btn-sm" onclick="addToCart(<?= $p['id'] ?>, <?= $p['min_order_qty'] ?>)">
                  <i class="bi bi-cart-plus"></i> <?= __('product.add_to_cart') ?>
                </button>
                <a href="/Green_Hat_B2B/pages/product-detail.php?slug=<?= e($p['slug']) ?>" class="btn btn-primary btn-sm">
                  <?= __('product.buy_now') ?>
                </a>
              </div>
            <?php else: ?>
              <div class="price-locked">
                <i class="bi bi-lock-fill"></i>
                <?php if (isLoggedIn()): ?>
                  Awaiting approval
                <?php else: ?>
                  <a href="/Green_Hat_B2B/auth/login.php"><?= __('product.price_locked') ?></a>
                <?php endif; ?>
              </div>
              <a href="/Green_Hat_B2B/pages/product-detail.php?slug=<?= e($p['slug']) ?>" class="btn btn-ghost btn-sm btn-full">
                <?= LANG==='bn'?'বিস্তারিত দেখুন':'View Details' ?>
              </a>
            <?php endif; ?>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>

<!-- ── Promo Banner 1 (Payment) ─────────────────────────────────────── -->
<?php
$pb1Heading = sectionCfg('promo_banner_1','heading', LANG==='bn'?'💳 বিকাশ, রকেট ও নগদে পেমেন্ট করুন':'💳 Pay with bKash, Rocket &amp; Nagad');
$pb1Sub     = sectionCfg('promo_banner_1','subtext',  LANG==='bn'?'বাংলাদেশের সব মোবাইল ব্যাংকিং ও SSL Commerz সাপোর্ট।':'All Bangladesh mobile banking &amp; SSL Commerz accepted.');
$pb1Cta     = sectionCfg('promo_banner_1','cta_label',LANG==='bn'?'বিনামূল্যে যোগ দিন':'Join Free');
$pb1Start   = sectionCfg('promo_banner_1','bg_start','#e2136e');
$pb1End     = sectionCfg('promo_banner_1','bg_end','#8332a4');
?>
<section style="background:linear-gradient(135deg,<?= $pb1Start ?>,<?= $pb1End ?>);padding:40px 0;margin:0"
         data-section="promo_banner_1">
  <div class="container" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:20px">
    <div style="color:#fff">
      <h3 style="font-size:24px;font-weight:800;margin-bottom:6px" data-ve="heading"><?= $pb1Heading ?></h3>
      <p style="color:rgba(255,255,255,.85);font-size:15px" data-ve="subtext"><?= $pb1Sub ?></p>
    </div>
    <a href="/Green_Hat_B2B/auth/register.php" class="btn btn-lg" style="background:#fff;color:#e2136e;font-weight:800">
      <i class="bi bi-person-plus-fill"></i> <span data-ve="cta"><?= $pb1Cta ?></span>
    </a>
  </div>
</section>

<!-- ── Promo Banner 2 (Volume Pricing) ──────────────────────────────── -->
<?php
$pb2Heading = sectionCfg('promo_banner_2','heading', LANG==='bn'?'পরিমাণ ভিত্তিক ছাড়':'Volume Pricing Unlocked');
$pb2Sub     = sectionCfg('promo_banner_2','subtext',  LANG==='bn'?'৫০+ ইউনিট অর্ডার করলে ৩০% পর্যন্ত সাশ্রয়।':'Order 50+ units on any product and save up to 30% automatically.');
$pb2Cta     = sectionCfg('promo_banner_2','cta_label',__('home.shop_now'));
$pb2Start   = sectionCfg('promo_banner_2','bg_start','#064e3b');
$pb2End     = sectionCfg('promo_banner_2','bg_end','#065f46');
?>
<section style="background:linear-gradient(135deg,<?= $pb2Start ?>,<?= $pb2End ?>);padding:36px 0"
         data-section="promo_banner_2">
  <div class="container" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:20px">
    <div style="color:#fff">
      <h3 style="font-size:22px;font-weight:800;margin-bottom:6px">
        <i class="bi bi-percent"></i> <span data-ve="heading"><?= $pb2Heading ?></span>
      </h3>
      <p style="color:rgba(255,255,255,.8)" data-ve="subtext"><?= $pb2Sub ?></p>
    </div>
    <a href="/Green_Hat_B2B/pages/products.php" class="btn btn-accent btn-lg">
      <i class="bi bi-bag-fill"></i> <span data-ve="cta"><?= $pb2Cta ?></span>
    </a>
  </div>
</section>

<!-- ── Recently Viewed ──────────────────────────────────────────────── -->
<?php if ($recentlyViewed): ?>
<section class="recently-section" data-section="recently_viewed">
  <div class="container">
    <div class="section-header">
      <h2 class="section-title accent" data-ve="section_title"><?= __('home.recently_viewed') ?></h2>
    </div>
    <div class="scroll-row">
      <?php foreach ($recentlyViewed as $p): ?>
        <div class="product-card">
          <a href="/Green_Hat_B2B/pages/product-detail.php?slug=<?= e($p['slug']) ?>">
            <div class="product-card-img">
              <img src="<?= productImageUrl($p['image']) ?>" alt="<?= e($p['name']) ?>"
                   onerror="this.onerror=null;this.src='/Green_Hat_B2B/assets/images/placeholder.php'">
            </div>
          </a>
          <div class="product-card-body">
            <div class="product-card-name"><?= e($p['name']) ?></div>
            <?php if (isLoggedIn() && isApproved()): ?>
              <div class="product-price" style="font-size:16px"><?= formatPrice((float)$p['base_price']) ?></div>
            <?php else: ?>
              <div class="price-locked">
                <i class="bi bi-lock-fill"></i>
                <?= isLoggedIn() ? 'Awaiting approval' : 'Login to see price' ?>
              </div>
            <?php endif; ?>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>
<?php endif; ?>

<!-- ── Custom Sections ───────────────────────────────────────────────── -->
<?php foreach ($customSections as $_cs):
    $_csCfg = json_decode($_cs['config'] ?? '{}', true) ?? [];
    $_csBg  = $_csCfg['bg_color'] ?? '';
    $_csKey = e($_cs['key']);
?>
<section class="page-section" data-section="<?= $_csKey ?>"
  style="padding:48px 0<?= $_csBg ? ';background:' . $_csBg : '' ?>">
  <?= renderProductSection($_cs['key'], $_csCfg) ?>
</section>
<?php endforeach; ?>

<!-- ── Why Shop With Us ─────────────────────────────────────────────── -->
<?php $_wuBg = sectionCfg('why_us','bg_color',''); ?>
<section class="trust-section" data-section="why_us"<?= $_wuBg ? ' style="background:' . $_wuBg . '"' : '' ?>>
  <div class="container">
    <div class="section-header" style="justify-content:center;margin-bottom:36px">
      <h2 class="section-title" style="font-size:28px" data-ve="section_title">
        <?= sectionCfg('why_us','section_title', LANG==='bn'?'কেন আমাদের সাথে কিনবেন?':'Why Shop With Us?') ?>
      </h2>
    </div>
    <div class="trust-grid">
      <?php
      $trustItems = [
        ['bi-cash-coin',        '#16a34a', LANG==='bn'?'ক্যাশ অন ডেলিভারি':'Cash on Delivery',  LANG==='bn'?'পণ্য পেলে তবেই টাকা দিন।':'Pay only when you receive your order.'],
        ['bi-phone',            '#e2136e', LANG==='bn'?'মোবাইল পেমেন্ট':'Mobile Payment',        LANG==='bn'?'বিকাশ, রকেট, নগদ সাপোর্ট।':'bKash, Rocket, Nagad supported.'],
        ['bi-shield-lock-fill', '#7c3aed', LANG==='bn'?'নিরাপদ পেমেন্ট':'Secure Payments',       LANG==='bn'?'SSL এনক্রিপশন সুরক্ষিত।':'Bank-grade encryption on every transaction.'],
        ['bi-truck-front-fill', '#f97316', LANG==='bn'?'দ্রুত ডেলিভারি':'Fast Delivery',          LANG==='bn'?'২-৫ কার্যদিবসে পৌঁছে দিই।':'Delivery across Bangladesh in 2-5 days.'],
        ['bi-graph-up-arrow',   '#db2777', LANG==='bn'?'পরিমাণ ছাড়':'Volume Discounts',           LANG==='bn'?'৩০% পর্যন্ত ছাড়।':'Save up to 30% automatically.'],
        ['bi-headset',          '#0891b2', LANG==='bn'?'২৪/৭ সাপোর্ট':'24/7 Support',             LANG==='bn'?'চ্যাট ও ফোনে সহায়তা।':'Dedicated B2B support via chat & phone.'],
        ['bi-patch-check-fill', '#65a30d', LANG==='bn'?'যাচাইকৃত বিক্রেতা':'Verified Vendors',   LANG==='bn'?'সব বিক্রেতা অনুমোদিত।':'All sellers vetted and approved.'],
        ['bi-bangladeshi-taka', '#d97706', LANG==='bn'?'সেরা মূল্য':'Best BDT Prices',            LANG==='bn'?'সেরা পাইকারি মূল্য।':'Best wholesale rates. No hidden fees.'],
      ];
      foreach ($trustItems as [$icon, $color, $title, $desc]): ?>
        <div class="trust-item">
          <div class="trust-icon" style="background:<?= $color ?>22;color:<?= $color ?>">
            <i class="bi <?= $icon ?>"></i>
          </div>
          <h4><?= $title ?></h4>
          <p><?= $desc ?></p>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
