<?php
// ============================================================
// FILE: index.php — Landing Page Utama
// Menampilkan: Hero, Layanan, Histori, Galeri, Produk Unggulan,
//              CTA, Lokasi Google Maps, Footer
// ============================================================

require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';

$pageTitle  = 'Beranda';
$activePage = 'home';

$pdo = db();

// ── Proses POST: tambah keranjang dari index ─────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['aksi_index'])) {
    $produkId = (int)($_POST['produk_id'] ?? 0);
    $sid      = session_id();
    $cekProd  = $pdo->prepare("SELECT id, stok FROM produk WHERE id=? AND is_aktif=1 LIMIT 1");
    $cekProd->execute([$produkId]);
    $prodData = $cekProd->fetch();

    if ($prodData && (float)$prodData['stok'] > 0) {
        $cek = $pdo->prepare("SELECT id, jumlah FROM keranjang WHERE session_id=? AND produk_id=?");
        $cek->execute([$sid, $produkId]);
        $existing = $cek->fetch();
        if ($existing) {
            $newJml = min($existing['jumlah'] + 1, (float)$prodData['stok']);
            $pdo->prepare("UPDATE keranjang SET jumlah=? WHERE id=?")->execute([$newJml, $existing['id']]);
        } else {
            $pdo->prepare("INSERT INTO keranjang (session_id, produk_id, jumlah) VALUES (?,?,1)")
                ->execute([$sid, $produkId]);
        }
        if (isset($_POST['langsung_checkout'])) {
            redirect(BASE_URL . '/checkout.php');
        }
    }
    redirect(BASE_URL . '/');
}

// ── Ambil Galeri (maks 8 foto terbaru) ──────────────────────
$stmtGaleri = $pdo->query("
    SELECT g.*, k.nama AS nama_kategori
    FROM galeri g
    LEFT JOIN kategori k ON g.kategori_id = k.id
    ORDER BY g.urutan ASC, g.created_at DESC
    LIMIT 8
");
$galeriList = $stmtGaleri->fetchAll();

// ── Ambil Produk Unggulan (8 produk aktif, random) ──────────
$stmtProduk = $pdo->query("
    SELECT p.*,
           k.nama AS nama_kategori,
           (SELECT nama_file FROM produk_foto
            WHERE produk_id = p.id ORDER BY urutan ASC LIMIT 1) AS foto_utama
    FROM produk p
    JOIN kategori k ON p.kategori_id = k.id
    WHERE p.is_aktif = 1 AND p.stok > 0
    ORDER BY RAND()
    LIMIT 8
");
$produkUnggulan = $stmtProduk->fetchAll();

// ── Data Statistik Toko ──────────────────────────────────────
$tahunBerdiri = TAHUN_BERDIRI;
$umurToko     = date('Y') - $tahunBerdiri;

// Hitung total pesanan selesai & produk
$totalProduk  = $pdo->query("SELECT COUNT(*) FROM produk WHERE is_aktif = 1")->fetchColumn();
$totalSelesai = $pdo->query("SELECT COUNT(*) FROM pesanan WHERE status = 'selesai'")->fetchColumn();

// ── Milestones Histori dari DB ───────────────────────────────
$milestoneRows = $pdo->query("
    SELECT * FROM histori_toko
    WHERE is_aktif = 1
    ORDER BY urutan ASC, tahun ASC
")->fetchAll();

$milestones = array_map(fn($r) => [
    'tahun' => $r['tahun'],
    'judul' => $r['judul'],
    'desc'  => $r['deskripsi'] ?? '',
], $milestoneRows);

// Fallback jika tabel belum ada / kosong
if (empty($milestones)) {
    $milestones = [
        ['tahun'=>2005,'judul'=>'Berdiri & Pertama Buka','desc'=>'Pak Budi memulai usaha dari kios sederhana.'],
        ['tahun'=>date('Y'),'judul'=>'Go Digital','desc'=>'Membuka toko online untuk melayani lebih luas.'],
    ];
}

// ── Pengaturan Hero dari DB ───────────────────────────────────
$heroCfg = [];
try {
    foreach ($pdo->query("SELECT kunci, nilai FROM pengaturan_hero")->fetchAll() as $r) {
        $heroCfg[$r['kunci']] = $r['nilai'];
    }
} catch (Exception $e) {
    // Tabel belum ada, pakai default
}

// ── Layanan Unggulan ─────────────────────────────────────────
$layanan = [
    ['icon' => 'bi-tree-fill',      'kelas' => 'icon-wood',    'judul' => 'Kusen Kayu',         'desc' => 'Kayu pilihan berkualitas tinggi, tahan lama dan tampilannya elegan.'],
    ['icon' => 'bi-square-half',    'kelas' => 'icon-alum',    'judul' => 'Kusen Aluminium',    'desc' => 'Ringan, anti karat, dan tersedia dalam berbagai warna pilihan.'],
    ['icon' => 'bi-grid-3x2-gap',   'kelas' => 'icon-gyp',     'judul' => 'Gypsum Board',       'desc' => 'Plafon dan partisi gypsum untuk hunian dan komersial.'],
    ['icon' => 'bi-tools',          'kelas' => 'icon-service',  'judul' => 'Jasa Pemasangan',    'desc' => 'Tim berpengalaman kami siap membantu pemasangan di lokasi Anda.'],
    ['icon' => 'bi-lightning-fill', 'kelas' => 'icon-fast',    'judul' => 'Pengiriman Cepat',   'desc' => 'Layanan pengiriman same-day untuk area Bogor dan sekitarnya.'],
    ['icon' => 'bi-tags-fill',      'kelas' => 'icon-price',   'judul' => 'Harga Bersaing',     'desc' => 'Langsung dari produsen, harga lebih terjangkau tanpa perantara.'],
];



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

<!-- ====================================================
     SECTION 1: HERO
     ==================================================== -->
<section class="hero-section">
  <div class="hero-bg" <?php if (!empty($heroCfg['hero_bg_url'])): ?>style="background-image:url('<?= e($heroCfg['hero_bg_url']) ?>')"<?php endif; ?>></div>

  <div class="container">
    <div class="row align-items-center">

      <!-- Konten Kiri -->
      <div class="col-lg-6 hero-content">
        <div class="hero-badge">
          <i class="bi bi-star-fill"></i>
          <?= e($heroCfg['hero_badge'] ?? 'Terpercaya Sejak ' . $tahunBerdiri) ?>
        </div>

        <h1 class="hero-title">
          <?= e($heroCfg['hero_judul_baris1'] ?? 'Kusen & Gypsum') ?><br>
          <span class="highlight"><?= e($heroCfg['hero_judul_baris2'] ?? 'Terbaik untuk Hunian Anda') ?></span>
        </h1>

        <p class="hero-subtitle">
          <?= e($heroCfg['hero_subtitle'] ?? 'Dari kusen kayu premium hingga gypsum modern — kami menyediakan solusi untuk kebutuhan bahan bangunan Anda.') ?>
        </p>

        <div class="hero-cta">
          <a href="<?= BASE_URL ?>/katalog.php" class="btn-primary-hero">
            <i class="bi bi-grid-3x3-gap-fill"></i>
            Lihat Katalog
          </a>
          <a href="#tentang" class="btn-outline-hero">
            <i class="bi bi-play-circle-fill"></i>
            Tentang Kami
          </a>
        </div>

        <!-- Statistik -->
        <div class="hero-stats">
          <div class="stat-item">
            <div class="stat-number" data-count="<?= $umurToko ?>" data-suffix="+">0</div>
            <div class="stat-label">Tahun<br>Pengalaman</div>
          </div>
          <div class="stat-item" style="border-left:1px solid rgba(255,255,255,.15);padding-left:2.5rem">
            <div class="stat-number" data-count="<?= max((int)$totalProduk, 50) ?>" data-suffix="+">0</div>
            <div class="stat-label">Varian<br>Produk</div>
          </div>
          <div class="stat-item" style="border-left:1px solid rgba(255,255,255,.15);padding-left:2.5rem">
            <div class="stat-number" data-count="<?= max((int)$totalSelesai, 500) ?>" data-suffix="+">0</div>
            <div class="stat-label">Pesanan<br>Selesai</div>
          </div>
        </div>
      </div><!-- /col kiri -->

      <!-- Kolom Kanan: Gambar -->
      <div class="col-lg-6 d-none d-lg-block">
        <div class="hero-image-card">
          <img
            src="<?= e($heroCfg['hero_img_utama'] ?? 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=800&q=80') ?>"
            alt="Kusen Berkualitas Budi Jaya"
            class="hero-img-main"
          >
          <!-- Badge floating di bawah gambar -->
          <div class="hero-img-badge">
            <div class="badge-icon">
              <i class="bi bi-patch-check-fill"></i>
            </div>
            <div>
              <strong>Kualitas Terjamin</strong><br>
              <span>Bahan pilihan &amp; bergaransi</span>
            </div>
          </div>
        </div>
      </div>

    </div><!-- /row -->
  </div><!-- /container -->
</section>

<!-- ====================================================
     SECTION 2: LAYANAN / KEUNGGULAN
     ==================================================== -->
<section class="section" id="layanan">
  <div class="container">

    <div class="text-center mb-5 reveal">
      <div class="section-label">Mengapa Kami</div>
      <h2 class="section-title">Solusi untuk Hunian Anda</h2>
      <p class="section-subtitle mx-auto">
        Dari bahan baku hingga pemasangan — semua tersedia dalam satu tempat
        dengan standar kualitas yang tidak pernah kami kompromikan.
      </p>
    </div>

    <div class="row g-4">
      <?php foreach ($layanan as $i => $l): ?>
        <div class="col-lg-4 col-md-6 reveal reveal-delay-<?= ($i % 4) + 1 ?>">
          <div class="layanan-card">
            <div class="layanan-icon <?= $l['kelas'] ?>">
              <i class="bi <?= $l['icon'] ?>"></i>
            </div>
            <h5><?= $l['judul'] ?></h5>
            <p><?= $l['desc'] ?></p>
          </div>
        </div>
      <?php endforeach; ?>
    </div>

  </div>
</section>

<!-- ====================================================
     SECTION 3: HISTORI / TENTANG TOKO
     ==================================================== -->
<section class="section section-alt" id="tentang">
  <div class="container">
    <div class="row justify-content-center g-5">

      <div class="col-lg-10 col-xl-8">
        <div class="mb-5 reveal text-center">
          <div class="section-label">Histori Kami</div>
          <h2 class="section-title mx-auto">Perjalanan Panjang<br>Penuh Dedikasi</h2>
          <p class="text-muted max-w-2xl mx-auto">
            Budi Jaya bukan sekadar toko kusen — kami adalah mitra terpercaya
            ribuan keluarga yang membangun rumah impian mereka. Inilah cerita kami.
          </p>
        </div>

        <div class="timeline">
          <?php foreach ($milestones as $m): ?>
            <div class="timeline-item">
              <div class="timeline-dot">
                <i class="bi bi-check-lg"></i>
              </div>
              <div class="timeline-year"><?= $m['tahun'] ?></div>
              <div class="timeline-title"><?= e($m['judul']) ?></div>
              <div class="timeline-desc"><?= e($m['desc']) ?></div>
            </div>
          <?php endforeach; ?>
        </div>

        <div class="mt-5 reveal text-center">
          <a href="<?= BASE_URL ?>/katalog.php" class="btn btn-primary-brand">
            <i class="bi bi-grid me-2"></i>Lihat Semua Produk
          </a>
        </div>
      </div>

    </div>
  </div>
</section>
<!-- ====================================================
     SECTION 4: PRODUK UNGGULAN
     ==================================================== -->
<?php if (!empty($produkUnggulan)): ?>
<section class="section">
  <div class="container">

    <div class="d-flex justify-content-between align-items-end mb-5 flex-wrap gap-3 reveal">
      <div>
        <div class="section-label">Produk Terpilih</div>
        <h2 class="section-title mb-0">Unggulan Kami</h2>
      </div>
      <a href="<?= BASE_URL ?>/katalog.php" class="btn btn-outline-secondary">
        Lihat Semua <i class="bi bi-arrow-right ms-1"></i>
      </a>
    </div>

    <div class="row g-3">
      <?php foreach ($produkUnggulan as $i => $p):
        $fotoUrl = $p['foto_utama']
          ? UPLOAD_URL . '/produk/' . e($p['foto_utama'])
          : 'https://images.unsplash.com/photo-1618219908412-a29a1bb7b86e?w=400&q=60';
      ?>
        <div class="col-lg-3 col-md-4 col-6 reveal reveal-delay-<?= ($i % 4) + 1 ?>">
          <div class="produk-card">
            <div class="produk-img-wrap">
              <img src="<?= $fotoUrl ?>" alt="<?= e($p['nama']) ?>" loading="lazy">
              <span class="produk-badge"><?= e($p['nama_kategori']) ?></span>
            </div>
            <div class="produk-body">
              <div class="produk-kat"><?= e($p['satuan'] === 'meter' ? 'Per meter lari' : 'Per ' . $p['satuan']) ?></div>
              <h3 class="produk-nama"><?= e($p['nama']) ?></h3>
              <div class="produk-harga">
                <?= formatRupiah($p['harga']) ?>
                <small>/<?= e($p['satuan']) ?></small>
              </div>
              <div class="produk-footer">
                <a href="<?= BASE_URL ?>/produk.php?slug=<?= e($p['slug']) ?>"
                   class="btn-produk btn-produk-primary">
                  <i class="bi bi-eye"></i> Detail
                </a>
                <!-- Tombol Keranjang AJAX -->
                <button type="button"
                        class="btn-produk btn-produk-outline btn-keranjang-ajax"
                        data-produk-id="<?= $p['id'] ?>"
                        title="Tambah ke Keranjang">
                  <i class="bi bi-cart-plus"></i>
                </button>
              </div>
              <!-- Tombol Beli Langsung -->
              <form method="POST" action="<?= BASE_URL ?>/" class="mt-2">
                <input type="hidden" name="aksi_index" value="1">
                <input type="hidden" name="langsung_checkout" value="1">
                <input type="hidden" name="produk_id" value="<?= $p['id'] ?>">
                <button type="submit"
                        class="btn btn-sm w-100 fw-semibold"
                        style="background:#D4A853;color:#fff;border:none;border-radius:8px;padding:.35rem;">
                  <i class="bi bi-lightning-fill me-1"></i>Beli Langsung
                </button>
              </form>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>

  </div>
</section>
<?php endif; ?>

<!-- ====================================================
     SECTION 5: GALERI PORTOFOLIO
     ==================================================== -->
<section class="section section-alt" id="galeri">
  <div class="container">

    <div class="text-center mb-5 reveal">
      <div class="section-label">Portofolio</div>
      <h2 class="section-title">Hasil Pemasangan Kami</h2>
      <p class="section-subtitle mx-auto">
        Berikut sebagian hasil
        pemasangan produk Budi Jaya di berbagai hunian dan gedung.
      </p>
    </div>

    <?php if (!empty($galeriList)): ?>
      <!-- Grid Galeri -->
      <div class="galeri-grid reveal">
        <?php foreach ($galeriList as $foto): ?>
          <div class="galeri-item">
            <img
              src="<?= UPLOAD_URL ?>/galeri/<?= e($foto['nama_file']) ?>"
              alt="<?= e($foto['judul']) ?>"
              class="galeri-img"
              loading="lazy"
            >
            <div class="galeri-overlay">
              <h6><?= e($foto['judul']) ?></h6>
              <?php if ($foto['nama_kategori']): ?>
                <small><i class="bi bi-tag me-1"></i><?= e($foto['nama_kategori']) ?></small>
              <?php endif; ?>
            </div>
          </div>
        <?php endforeach; ?>
      </div>

    <?php else: ?>
      <!-- Placeholder galeri saat DB kosong (gunakan foto Unsplash) -->
      <?php
        $placeholders = [
          ['https://images.unsplash.com/photo-1588880331179-bc9b93a8cb5e?w=800&q=70', 'Pemasangan Kusen Pintu',    'Kusen Kayu'],
          ['https://images.unsplash.com/photo-1615571022219-eb45cf7faa9d?w=600&q=70', 'Plafon Gypsum Modern',     'Gypsum Board'],
          ['https://images.unsplash.com/photo-1631889993959-41b4e9c6e3c5?w=500&q=70', 'Kusen Aluminium Jendela',  'Kusen Aluminium'],
          ['https://images.unsplash.com/photo-1600566752355-35792bedcfea?w=600&q=70', 'Interior Rumah Minimalis', 'Kusen Kayu'],
          ['https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=800&q=70', 'Pintu Kayu Premium',       'Kusen Kayu'],
          ['https://images.unsplash.com/photo-1559628233-100c798642d5?w=600&q=70', 'Partisi Gypsum Kantor',    'Gypsum Board'],
          ['https://images.unsplash.com/photo-1610576706429-9c2fdc3a1efa?w=600&q=70', 'Showroom Display',         'Toko'],
          ['https://images.unsplash.com/photo-1582268611958-ebfd161ef9cf?w=500&q=70', 'Kusen Jendela Sliding',   'Kusen Aluminium'],
        ];
      ?>
      <div class="galeri-grid reveal">
        <?php foreach ($placeholders as [$src, $judul, $kat]): ?>
          <div class="galeri-item">
            <img src="<?= $src ?>" alt="<?= e($judul) ?>" class="galeri-img" loading="lazy">
            <div class="galeri-overlay">
              <h6><?= e($judul) ?></h6>
              <small><i class="bi bi-tag me-1"></i><?= e($kat) ?></small>
            </div>
          </div>
        <?php endforeach; ?>
      </div>

      <!-- Pesan untuk admin -->
      <?php if (isAdmin()): ?>
        <div class="text-center mt-4">
          <div class="alert alert-info d-inline-flex align-items-center gap-2">
            <i class="bi bi-info-circle-fill"></i>
            Foto galeri di atas adalah placeholder. Tambahkan foto nyata di
            <a href="<?= BASE_URL ?>/admin/galeri.php" class="fw-bold">Admin → Galeri</a>.
          </div>
        </div>
      <?php endif; ?>
    <?php endif; ?>

  </div>
</section>

<!-- ====================================================
     SECTION 6: CTA BANNER
     ==================================================== -->


<!-- ====================================================
     SECTION 7: LOKASI & KONTAK
     ==================================================== -->
<section class="maps-section" id="lokasi">
  <div class="container">

    <div class="row align-items-center g-5">

      <!-- Info Kontak -->
      <div class="col-lg-5 reveal">
        <div class="section-label">Temukan Kami</div>
        <h2 class="section-title" style="color:white;">Kunjungi Toko Kami</h2>
        <p style="color:rgba(255,255,255,.65);" class="mb-4">
          Toko kami buka setiap hari Senin–Sabtu. Anda bisa langsung datang
          untuk melihat sampel produk, atau hubungi kami terlebih dahulu.
        </p>

        <div class="d-flex flex-column gap-3">

          <div class="contact-card">
            <div class="contact-icon" style="background:rgba(212,168,83,.15);color:var(--accent);">
              <i class="bi bi-geo-alt-fill"></i>
            </div>
            <div>
              <div class="contact-label">Alamat Toko</div>
              <div class="contact-value"><?= ALAMAT_TOKO ?></div>
              <a href="<?= GMAPS_LINK ?>" target="_blank" style="color:rgba(255,255,255,.5);font-size:.82rem;">
                <i class="bi bi-arrow-up-right-square me-1"></i>Buka di Google Maps
              </a>
            </div>
          </div>


          

          <div class="contact-card">
            <div class="contact-icon" style="background:rgba(100,149,237,.15);color:#6495ED;">
              <i class="bi bi-clock-fill"></i>
            </div>
            <div>
              <div class="contact-label">Jam Operasional</div>
              <div class="contact-value">Senin – Sabtu: 08.00 – 17.00 WIB</div>
              <span style="color:rgba(255,255,255,.4);font-size:.82rem;">Minggu: Tutup</span>
            </div>
          </div>

        </div><!-- /cards -->
      </div>

      <!-- Kolom placeholder (balance layout) -->
      <div class="col-lg-7 reveal reveal-delay-2">
        <div class="d-flex align-items-center justify-content-center h-100">
          <div class="text-center" style="color:rgba(255,255,255,.5);">
            <i class="bi bi-map" style="font-size:4rem;color:var(--accent);"></i>
            <p class="mt-3 mb-0">Lihat peta di bawah</p>
          </div>
        </div>
      </div>

    </div>
  </div>

  <!-- Google Maps Embed — full width di bawah -->
  <div class="maps-iframe-wrap mt-4 reveal">
    <iframe
      src="<?= GMAPS_EMBED ?>"
      width="100%"
      height="450"
      style="border:0;"
      allowfullscreen=""
      loading="lazy"
      referrerpolicy="no-referrer-when-downgrade"
      title="Lokasi Toko Kusen &amp; Gypsum Budi Jaya"
    ></iframe>
  </div>
</section>

<!-- Toast notifikasi keranjang -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index:9999">
  <div id="toastKeranjang" class="toast align-items-center text-white border-0"
       role="alert" aria-live="assertive" data-bs-delay="2500">
    <div class="d-flex">
      <div class="toast-body" id="toastPesan">
        <i class="bi bi-cart-check-fill me-2"></i>Produk ditambahkan!
      </div>
      <button type="button" class="btn-close btn-close-white me-2 m-auto"
              data-bs-dismiss="toast"></button>
    </div>
  </div>
</div>

<script>
(function () {
  const AJAX_URL = '<?= BASE_URL ?>/keranjang_ajax.php';

  document.addEventListener('click', function (e) {
    const btn = e.target.closest('.btn-keranjang-ajax');
    if (!btn) return;

    const produkId = btn.dataset.produkId;
    const icon     = btn.querySelector('i');

    // Loading state
    btn.disabled = true;
    icon.className = 'bi bi-hourglass-split';

    const fd = new FormData();
    fd.append('produk_id', produkId);

    fetch(AJAX_URL, { method: 'POST', body: fd })
      .then(r => r.json())
      .then(data => {
        if (data.success) {
          // Update badge keranjang di navbar
          const badge = document.querySelector('.badge-cart');
          if (badge) {
            badge.textContent = data.jumlah_keranjang;
          } else {
            // Buat badge baru kalau belum ada
            const cartBtn = document.querySelector('.btn-cart');
            if (cartBtn) {
              const b = document.createElement('span');
              b.className = 'badge-cart';
              b.textContent = data.jumlah_keranjang;
              cartBtn.appendChild(b);
            }
          }

          // Tampilkan toast
          document.getElementById('toastPesan').innerHTML =
            '<i class="bi bi-cart-check-fill me-2"></i>' + data.pesan;
          const toastEl = document.getElementById('toastKeranjang');
          toastEl.classList.remove('bg-danger');
          toastEl.classList.add('bg-success');
          new bootstrap.Toast(toastEl).show();

          // Animasi tombol sukses
          icon.className = 'bi bi-check-lg';
          setTimeout(() => { icon.className = 'bi bi-cart-plus'; btn.disabled = false; }, 1500);
        } else {
          document.getElementById('toastPesan').innerHTML =
            '<i class="bi bi-exclamation-circle me-2"></i>' + data.pesan;
          const toastEl = document.getElementById('toastKeranjang');
          toastEl.classList.remove('bg-success');
          toastEl.classList.add('bg-danger');
          new bootstrap.Toast(toastEl).show();
          icon.className = 'bi bi-cart-plus';
          btn.disabled = false;
        }
      })
      .catch(() => {
        icon.className = 'bi bi-cart-plus';
        btn.disabled = false;
      });
  });
})();
</script>

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