<?php
// ============================================================
// FILE: katalog.php
// Halaman Katalog Produk — style Shopee
// Fitur: Sidebar filter kategori, search, sort, pagination,
//        card produk responsif dengan quick-view overlay
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';

$pdo = db();

// ── Parameter GET ────────────────────────────────────────────
$q       = trim($_GET['q']        ?? '');
$katSlug = trim($_GET['kategori'] ?? '');
$sort    = $_GET['sort']          ?? 'terbaru';
$page    = max(1, (int)($_GET['page'] ?? 1));
$perPage = 16;
$offset  = ($page - 1) * $perPage;

// ── Ambil semua kategori (untuk sidebar) + hitung produk ─────
$kategoriList = $pdo->query("
    SELECT k.*, COUNT(p.id) AS jml_produk
    FROM kategori k
    LEFT JOIN produk p ON p.kategori_id = k.id AND p.is_aktif = 1
    GROUP BY k.id ORDER BY k.nama ASC
")->fetchAll();

// ── Cari kategori aktif ───────────────────────────────────────
$kategoriAktif = null;
foreach ($kategoriList as $k) {
    if ($k['slug'] === $katSlug) { $kategoriAktif = $k; break; }
}

// ── Bangun WHERE clause ───────────────────────────────────────
$where  = ['p.is_aktif = 1'];
$params = [];

if ($q) {
    $where[]  = '(p.nama LIKE ? OR p.deskripsi LIKE ? OR k.nama LIKE ?)';
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
}
if ($kategoriAktif) {
    $where[]  = 'p.kategori_id = ?';
    $params[] = $kategoriAktif['id'];
}

$whereSQL = 'WHERE ' . implode(' AND ', $where);

// ── ORDER BY ─────────────────────────────────────────────────
$orderSQL = match ($sort) {
    'harga_asc'  => 'p.harga ASC',
    'harga_desc' => 'p.harga DESC',
    'nama_asc'   => 'p.nama ASC',
    'stok_ada'   => 'p.stok DESC',
    default      => 'p.created_at DESC',
};

// ── Hitung total & ambil produk ───────────────────────────────
$stmtTotal = $pdo->prepare("SELECT COUNT(*) FROM produk p JOIN kategori k ON p.kategori_id=k.id $whereSQL");
$stmtTotal->execute($params);
$totalProduk = (int) $stmtTotal->fetchColumn();
$totalPage   = max(1, (int) ceil($totalProduk / $perPage));
$page        = min($page, $totalPage);

$stmtProd = $pdo->prepare("
    SELECT
        p.id, p.nama, p.slug, p.harga, p.satuan, p.stok,
        p.stok_minimum, p.deskripsi, p.created_at,
        k.nama  AS nama_kategori,
        k.slug  AS slug_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
    $whereSQL
    ORDER BY $orderSQL
    LIMIT $perPage OFFSET $offset
");
$stmtProd->execute($params);
$produkList = $stmtProd->fetchAll();

// ── Jumlah total semua produk (untuk "Semua" di sidebar) ─────
$totalSemua = (int) $pdo->query("SELECT COUNT(*) FROM produk WHERE is_aktif=1")->fetchColumn();

// ── Proses POST: tambah keranjang dari katalog ───────────────
$flashKeranjang = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['aksi_katalog'])) {
    $produkId  = (int)($_POST['produk_id'] ?? 0);
    $aksi      = $_POST['aksi_katalog'];
    $jumlah    = 1; // default 1 unit dari katalog
    $sid       = session_id();

    $cekProd = $pdo->prepare("SELECT id, stok, satuan FROM produk WHERE id=? AND is_aktif=1 LIMIT 1");
    $cekProd->execute([$produkId]);
    $prodData = $cekProd->fetch();

    if ($prodData && (float)$prodData['stok'] > 0) {
        // Cek apakah sudah ada di keranjang
        $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'] + $jumlah, (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 (?,?,?)")
                ->execute([$sid, $produkId, $jumlah]);
        }

        if ($aksi === 'beli_langsung') {
            redirect(BASE_URL . '/checkout.php');
        } else {
            // Kembali ke halaman katalog yang sama dengan flash message
            setFlash('success', 'Produk berhasil ditambahkan ke keranjang.');
            redirect(BASE_URL . '/katalog.php?' . http_build_query(array_filter([
                'q'        => $q,
                'kategori' => $katSlug,
                'sort'     => $sort,
                'page'     => $page,
            ])));
        }
    }
}

// ── Bangun URL dasar (tanpa page & sort) untuk pagination ────
function buildUrl(array $override = []): string {
    $params = array_filter(array_merge([
        'q'        => trim($_GET['q']        ?? ''),
        'kategori' => trim($_GET['kategori'] ?? ''),
        'sort'     => $_GET['sort']          ?? 'terbaru',
    ], $override));
    return BASE_URL . '/katalog.php?' . http_build_query($params);
}

$pageTitle  = $kategoriAktif ? e($kategoriAktif['nama']) : 'Katalog Produk';
$activePage = 'katalog';

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

<div class="katalog-hero">
  <div class="container">
    <nav aria-label="breadcrumb" class="mb-2">
      <ol class="breadcrumb katalog-breadcrumb mb-0">
        <li class="breadcrumb-item">
          <a href="<?= BASE_URL ?>"><i class="bi bi-house-door me-1"></i>Beranda</a>
        </li>
        <li class="breadcrumb-item <?= !$kategoriAktif ? 'active' : '' ?>">
          <a href="<?= BASE_URL ?>/katalog.php">Katalog</a>
        </li>
        <?php if ($kategoriAktif): ?>
          <li class="breadcrumb-item active"><?= e($kategoriAktif['nama']) ?></li>
        <?php endif; ?>
      </ol>
    </nav>

    <div class="d-flex align-items-end justify-content-between flex-wrap gap-3">
      <div>
        <h1 class="katalog-hero-title">
          <?php if ($q): ?>
            Hasil Pencarian: "<em><?= e($q) ?></em>"
          <?php elseif ($kategoriAktif): ?>
            <?= e($kategoriAktif['nama']) ?>
          <?php else: ?>
            Semua Produk
          <?php endif; ?>
        </h1>
        <p class="katalog-hero-sub mb-0">
          <?= number_format($totalProduk) ?> produk ditemukan
          <?php if ($page > 1): ?>
            · Halaman <?= $page ?> dari <?= $totalPage ?>
          <?php endif; ?>
        </p>
      </div>

      <?php if ($q): ?>
        <a href="<?= BASE_URL ?>/katalog.php<?= $katSlug ? '?kategori=' . urlencode($katSlug) : '' ?>"
           class="btn btn-outline-light btn-sm">
          <i class="bi bi-x-circle me-1"></i>Hapus Pencarian
        </a>
      <?php endif; ?>
    </div>
  </div>
</div>

<div class="container py-4">

  <div class="d-lg-none mb-3">
    <button class="btn btn-outline-secondary w-100 fw-semibold"
            type="button" data-bs-toggle="collapse" data-bs-target="#sidebarFilter">
      <i class="bi bi-funnel-fill me-2"></i>Filter & Kategori
      <?php if ($kategoriAktif): ?>
        <span class="badge bg-primary ms-2"><?= e($kategoriAktif['nama']) ?></span>
      <?php endif; ?>
    </button>
  </div>

  <div class="row g-4">

    <div class="col-lg-3">
      <div class="collapse d-lg-block" id="sidebarFilter">

        <div class="filter-card mb-3">
          <div class="filter-heading">
            <i class="bi bi-grid-3x3-gap-fill me-2"></i>Kategori Produk
          </div>
          <ul class="filter-list">
            <li>
              <a href="<?= buildUrl(['kategori' => '', 'page' => 1]) ?>"
                 class="filter-link <?= !$kategoriAktif ? 'active' : '' ?>">
                <span class="filter-link-text">
                  <i class="bi bi-collection me-2"></i>Semua Produk
                </span>
                <span class="filter-count"><?= $totalSemua ?></span>
              </a>
            </li>
            <?php foreach ($kategoriList as $kat): ?>
              <li>
                <a href="<?= buildUrl(['kategori' => $kat['slug'], 'page' => 1]) ?>"
                   class="filter-link <?= $katSlug === $kat['slug'] ? 'active' : '' ?>">
                  <span class="filter-link-text">
                    <i class="bi bi-tag me-2"></i><?= e($kat['nama']) ?>
                  </span>
                  <span class="filter-count"><?= $kat['jml_produk'] ?></span>
                </a>
              </li>
            <?php endforeach; ?>
          </ul>
        </div><div class="filter-card mb-3">
          <div class="filter-heading">
            <i class="bi bi-sort-down me-2"></i>Urutkan
          </div>
          <ul class="filter-list">
            <?php
              $sortOptions = [
                'terbaru'    => ['icon' => 'clock-history',      'label' => 'Terbaru'],
                'harga_asc'  => ['icon' => 'sort-numeric-down',  'label' => 'Harga: Terendah'],
                'harga_desc' => ['icon' => 'sort-numeric-up',    'label' => 'Harga: Tertinggi'],
                'nama_asc'   => ['icon' => 'sort-alpha-down',    'label' => 'Nama A–Z'],
                'stok_ada'   => ['icon' => 'box-seam',           'label' => 'Stok Tersedia'],
              ];
              foreach ($sortOptions as $val => $opt):
            ?>
              <li>
                <a href="<?= buildUrl(['sort' => $val, 'page' => 1]) ?>"
                   class="filter-link <?= $sort === $val ? 'active' : '' ?>">
                  <span class="filter-link-text">
                    <i class="bi bi-<?= $opt['icon'] ?> me-2"></i><?= $opt['label'] ?>
                  </span>
                  <?php if ($sort === $val): ?>
                    <i class="bi bi-check-lg text-primary"></i>
                  <?php endif; ?>
                </a>
              </li>
            <?php endforeach; ?>
          </ul>
        </div></div></div><div class="col-lg-9">

      <div class="katalog-toolbar mb-4">
        <p class="toolbar-count mb-0">
          Menampilkan
          <strong><?= (($page-1)*$perPage)+1 ?>–<?= min($page*$perPage, $totalProduk) ?></strong>
          dari <strong><?= number_format($totalProduk) ?></strong> produk
        </p>
        <div class="d-flex align-items-center gap-2">
          <label class="form-label mb-0 small text-muted fw-semibold d-none d-sm-block">Urutkan:</label>
          <select class="form-select form-select-sm toolbar-sort"
                  onchange="window.location.href=this.value">
            <?php foreach ($sortOptions as $val => $opt): ?>
              <option value="<?= buildUrl(['sort' => $val, 'page' => 1]) ?>"
                      <?= $sort === $val ? 'selected' : '' ?>>
                <?= $opt['label'] ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <?php if (empty($produkList)): ?>
        <div class="empty-state">
          <div class="empty-state-icon">
            <i class="bi bi-search"></i>
          </div>
          <h4>Produk Tidak Ditemukan</h4>
          <p class="text-muted">
            <?php if ($q): ?>
              Tidak ada produk yang cocok dengan "<strong><?= e($q) ?></strong>".
              Coba kata kunci lain atau lihat semua kategori.
            <?php else: ?>
              Belum ada produk di kategori ini.
            <?php endif; ?>
          </p>
          <a href="<?= BASE_URL ?>/katalog.php" class="btn btn-primary-brand mt-2">
            <i class="bi bi-grid me-2"></i>Lihat Semua Produk
          </a>
        </div>

      <?php else: ?>
        <div class="row g-3" id="produkGrid">
          <?php foreach ($produkList as $idx => $p):
            // Foto utama
            $fotoUrl = $p['foto_utama']
              ? UPLOAD_URL . '/produk/' . e($p['foto_utama'])
              : 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=500&q=75';

            // Status stok
            $habis      = (float)$p['stok'] <= 0;
            $stokSedikit = !$habis && (float)$p['stok'] <= (float)$p['stok_minimum'];

            // Cuplikan deskripsi (60 karakter)
            $cuplik = mb_strlen($p['deskripsi']) > 60
              ? mb_substr($p['deskripsi'], 0, 60) . '…'
              : $p['deskripsi'];
          ?>
            <div class="col-xl-3 col-lg-4 col-md-4 col-6 produk-col"
                 data-aos-delay="<?= ($idx % 4) * 60 ?>">
              <article class="produk-card <?= $habis ? 'produk-card--habis' : '' ?>">

                <a href="<?= BASE_URL ?>/produk.php?slug=<?= e($p['slug']) ?>"
                   class="produk-img-link" tabindex="-1">
                  <div class="produk-img-wrap">
                    <img src="<?= $fotoUrl ?>"
                         alt="<?= e($p['nama']) ?>"
                         class="produk-img"
                         loading="lazy">

                    <?php if ($habis): ?>
                      <div class="produk-label produk-label--habis">
                        <i class="bi bi-x-circle me-1"></i>Stok Habis
                      </div>
                    <?php elseif ($stokSedikit): ?>
                      <div class="produk-label produk-label--sedikit">
                        <i class="bi bi-fire me-1"></i>Hampir Habis
                      </div>
                    <?php endif; ?>

                    <div class="produk-kat-label"><?= e($p['nama_kategori']) ?></div>

                    <div class="produk-hover-overlay">
                      <div class="produk-hover-btn">
                        <i class="bi bi-eye-fill me-2"></i>Lihat Detail
                      </div>
                    </div>
                  </div>
                </a>

                <div class="produk-body">
                  <a href="<?= BASE_URL ?>/produk.php?slug=<?= e($p['slug']) ?>"
                     class="produk-nama-link">
                    <h3 class="produk-nama"><?= e($p['nama']) ?></h3>
                  </a>

                  <p class="produk-cuplik"><?= e($cuplik) ?></p>

                  <div class="produk-footer">
                    <div class="produk-harga-wrap">
                      <div class="produk-harga"><?= formatRupiah($p['harga']) ?></div>
                      <div class="produk-satuan">/ <?= e($p['satuan']) ?></div>
                    </div>

                    <?php if (!$habis): ?>
                      <!-- Tombol Keranjang AJAX -->
                      <button type="button"
                              class="produk-btn-detail btn-keranjang-ajax"
                              data-produk-id="<?= $p['id'] ?>"
                              title="Tambah ke Keranjang">
                        <i class="bi bi-cart-plus-fill"></i>
                      </button>
                    <?php else: ?>
                      <span class="produk-btn-detail produk-btn-detail--disabled" aria-disabled="true">
                        <i class="bi bi-x-circle"></i>
                      </span>
                    <?php endif; ?>
                  </div>

                  <?php if (!$habis): ?>
                    <!-- Tombol Beli Langsung -->
                    <form method="POST" class="mt-2">
                      <input type="hidden" name="produk_id" value="<?= $p['id'] ?>">
                      <input type="hidden" name="aksi_katalog" value="beli_langsung">
                      <button type="submit" class="btn btn-primary-brand btn-sm w-100 fw-semibold">
                        <i class="bi bi-lightning-fill me-1"></i>Beli Langsung
                      </button>
                    </form>
                  <?php endif; ?>

                  <?php if (!$habis): ?>
                    <div class="produk-stok-info">
                      <i class="bi bi-check-circle-fill <?= $stokSedikit ? 'text-warning' : 'text-success' ?> me-1"></i>
                      <span>Stok: <?= number_format($p['stok'], ($p['satuan']==='meter'?1:0)) ?> <?= e($p['satuan']) ?></span>
                    </div>
                  <?php endif; ?>
                </div></article>
            </div>
          <?php endforeach; ?>
        </div><?php if ($totalPage > 1): ?>
          <nav class="mt-5 d-flex justify-content-center" aria-label="Navigasi halaman">
            <ul class="pagination pagination-brand">

              <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                <a class="page-link page-link-nav"
                   href="<?= buildUrl(['page' => $page - 1]) ?>"
                   aria-label="Sebelumnya">
                  <i class="bi bi-chevron-left"></i>
                </a>
              </li>

              <?php
                $start = max(1, $page - 2);
                $end   = min($totalPage, $page + 2);
              ?>
              <?php if ($start > 1): ?>
                <li class="page-item">
                  <a class="page-link" href="<?= buildUrl(['page' => 1]) ?>">1</a>
                </li>
                <?php if ($start > 2): ?>
                  <li class="page-item disabled"><span class="page-link">…</span></li>
                <?php endif; ?>
              <?php endif; ?>

              <?php for ($i = $start; $i <= $end; $i++): ?>
                <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                  <a class="page-link" href="<?= buildUrl(['page' => $i]) ?>"><?= $i ?></a>
                </li>
              <?php endfor; ?>

              <?php if ($end < $totalPage): ?>
                <?php if ($end < $totalPage - 1): ?>
                  <li class="page-item disabled"><span class="page-link">…</span></li>
                <?php endif; ?>
                <li class="page-item">
                  <a class="page-link" href="<?= buildUrl(['page' => $totalPage]) ?>"><?= $totalPage ?></a>
                </li>
              <?php endif; ?>

              <li class="page-item <?= $page >= $totalPage ? 'disabled' : '' ?>">
                <a class="page-link page-link-nav"
                   href="<?= buildUrl(['page' => $page + 1]) ?>"
                   aria-label="Berikutnya">
                  <i class="bi bi-chevron-right"></i>
                </a>
              </li>

            </ul>
          </nav>
        <?php endif; ?>

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

<!-- 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');

    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 => {
        const toastEl = document.getElementById('toastKeranjang');
        document.getElementById('toastPesan').innerHTML = data.success
          ? '<i class="bi bi-cart-check-fill me-2"></i>' + data.pesan
          : '<i class="bi bi-exclamation-circle me-2"></i>' + data.pesan;
        toastEl.classList.toggle('bg-success', data.success);
        toastEl.classList.toggle('bg-danger',  !data.success);
        new bootstrap.Toast(toastEl).show();

        if (data.success) {
          const badge = document.querySelector('.badge-cart');
          if (badge) {
            badge.textContent = data.jumlah_keranjang;
          } else {
            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);
            }
          }
          icon.className = 'bi bi-check-lg';
          setTimeout(() => { icon.className = 'bi bi-cart-plus-fill'; btn.disabled = false; }, 1500);
        } else {
          icon.className = 'bi bi-cart-plus-fill';
          btn.disabled = false;
        }
      })
      .catch(() => { icon.className = 'bi bi-cart-plus-fill'; btn.disabled = false; });
  });
})();
</script>

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