<?php
/**
 * SHOP VIEW (SEARCH RESULT)
 * - Tidak skip produk stok 0 (biar jasa/digital tetap tampil)
 * - Tetap exclude produk yang punya variasi (sesuai file lama)
 */

$page    = max(1, (int) (request()->getGet("page") ?: 1));
$orderby = request()->getGet("orderby") ?: "id DESC";
$cariRaw = trim((string) (request()->getGet("cari") ?: ""));
$perpage = 12;

// daftar id produk yang punya variasi (sesuai shop lama)
$notin = [];
$dbvar = $db->table("produkvariasi")->select("idproduk")->groupBy("idproduk")->get();
foreach ($dbvar->getResult() as $not) {
  $notin[] = (int) $not->idproduk;
}

// ====== QUERY BUILDER (dibuat 2x: total & paging, biar aman) ======
$buildQuery = function () use ($db, $cariRaw, $notin) {
  $builder = $db->table("produk")->where("status", 1);

  if ($cariRaw !== "") {
    $builder->groupStart()
      ->like("nama", $cariRaw)
      ->orLike("deskripsi", $cariRaw)
      ->orLike("harga", $cariRaw)
      ->orLike("hargareseller", $cariRaw)
      ->orLike("hargaagen", $cariRaw)
      ->orLike("hargadistri", $cariRaw)
      ->groupEnd();
  }

  // sesuai versi lama: produk yang punya variasi di-exclude dari list utama
  if (count($notin) > 0) {
    $builder->whereNotIn("id", $notin);
  }

  return $builder;
};

// total rows
$dbs = $buildQuery()->get();
$totalRows = $dbs->getNumRows();

// paging rows
$dbResult = $buildQuery()->orderBy($orderby)->limit($perpage, ($page - 1) * $perpage)->get();

$level = (int) (session()->get('lvl') ?? 0);

// helper ambil harga sesuai level
$getPriceByLevel = function ($r) use ($level) {
  if ($level === 5 && isset($r->hargadistri))  return (float)$r->hargadistri;
  if ($level === 4 && isset($r->hargaagensp))  return (float)$r->hargaagensp;
  if ($level === 3 && isset($r->hargaagen))    return (float)$r->hargaagen;
  if ($level === 2 && isset($r->hargareseller))return (float)$r->hargareseller;
  return (float)$r->harga;
};
?>

<style>
/* ===== Scoped styling khusus halaman shop (tidak ganggu halaman lain) ===== */
.pm-shop { padding: 22px 0 34px; }
.pm-shop .pm-shop-head{ width:min(1100px, calc(100% - 32px)); margin: 0 auto 14px; }
.pm-shop .pm-shop-title{ font-size: 28px; font-weight: 800; letter-spacing:.2px; margin:0; }
.pm-shop .pm-shop-sub{ margin-top:4px; opacity:.85; }

.pm-shop .pm-shop-panel{
  width:min(1100px, calc(100% - 32px));
  margin: 14px auto 0;
  border-radius: 18px;
  padding: 16px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255,255,255,.08);
  background: rgba(255,255,255,.04);
}

.pm-shop .pm-grid{
  display:grid;
  grid-template-columns: repeat(4, minmax(0,1fr));
  gap: 14px;
}

@media (max-width: 1100px){ .pm-shop .pm-grid{ grid-template-columns: repeat(3, minmax(0,1fr)); } }
@media (max-width: 760px){ .pm-shop .pm-grid{ grid-template-columns: repeat(2, minmax(0,1fr)); } }
@media (max-width: 420px){ .pm-shop .pm-grid{ grid-template-columns: 1fr; } }

.pm-shop .pm-card{
  position: relative;
  border-radius: 16px;
  overflow: hidden;
  border: 1px solid rgba(255,255,255,.08);
  background: rgba(255,255,255,.05);
  transition: transform .15s ease, border-color .15s ease, background .15s ease;
}
.pm-shop .pm-card:hover{
  transform: translateY(-2px);
  border-color: rgba(255,255,255,.14);
  background: rgba(255,255,255,.07);
}

.pm-shop .pm-card a{ color: inherit; text-decoration:none; display:block; padding: 14px; }
.pm-shop .pm-row{ display:flex; gap: 12px; align-items:center; }
.pm-shop .pm-thumb{
  width: 54px; height:54px; border-radius: 12px;
  background: rgba(255,255,255,.06);
  border: 1px solid rgba(255,255,255,.10);
  display:flex; align-items:center; justify-content:center;
  overflow:hidden;
  flex: 0 0 auto;
}
.pm-shop .pm-thumb img{ width: 100%; height:100%; object-fit: cover; display:block; }
.pm-shop .pm-meta{ min-width:0; flex:1; }
.pm-shop .pm-name{ font-weight: 800; font-size: 14px; line-height: 1.25; margin: 0; }
.pm-shop .pm-desc{ margin-top:4px; font-size: 12px; opacity: .75; white-space: nowrap; overflow:hidden; text-overflow: ellipsis; }
.pm-shop .pm-price{
  margin-top: 10px;
  font-weight: 900;
  letter-spacing:.2px;
  font-size: 16px;
}
.pm-shop .pm-pill{
  display:inline-flex; align-items:center; gap:6px;
  border-radius: 999px;
  padding: 7px 10px;
  border: 1px solid rgba(255,255,255,.12);
  background: rgba(0,0,0,.15);
  font-size: 12px;
  margin-top: 10px;
  opacity:.9;
}

.pm-shop .pm-badge-out{
  position:absolute; top:10px; right:10px;
  font-size: 12px; font-weight: 800;
  padding: 6px 10px;
  border-radius: 999px;
  background: rgba(255,255,255,.12);
  border: 1px solid rgba(255,255,255,.18);
}
.pm-shop .pm-badge-flash{
  position:absolute; top:10px; left:10px;
  font-size: 11px; font-weight: 800;
  padding: 5px 9px;
  border-radius: 999px;
  background: linear-gradient(135deg, #ff2d55, #ff6a00);
  color: #fff;
  z-index: 2;
}
.pm-shop .pm-badge-discount{
  position:absolute; top:10px; right:10px;
  font-size: 12px; font-weight: 900;
  padding: 5px 9px;
  border-radius: 999px;
  background: #dc2626;
  color: #fff;
  z-index: 2;
}
.pm-shop .pm-rating{
  display:flex; align-items:center; gap:6px;
  margin-top: 8px;
  font-size: 12px;
}
.pm-shop .pm-rating-score{
  background: rgba(245,158,11,.18);
  color: #f59e0b;
  font-weight: 800;
  padding: 2px 7px;
  border-radius: 999px;
}
.pm-shop .pm-rating-stars{
  color: #f59e0b;
  letter-spacing: 1px;
}
.pm-shop .pm-price-old{
  margin-top: 10px;
  font-size: 12px;
  text-decoration: line-through;
  opacity: .65;
}
.pm-shop .pm-price{ color: #16a34a; }
.pm-shop .pm-ulasan{
  margin-top: 4px;
  font-size: 12px;
  opacity: .75;
}

.pm-shop .pm-empty{
  padding: 26px 14px;
  text-align:center;
  border-radius: 16px;
  border: 1px dashed rgba(255,255,255,.18);
  background: rgba(255,255,255,.03);
  opacity:.95;
}
.pm-shop .pm-empty h3{ margin:0 0 6px; font-weight: 900; }
.pm-shop .pm-empty p{ margin:0; opacity:.8; }

.pm-shop .pm-pagination{ width:min(1100px, calc(100% - 32px)); margin: 14px auto 0; }

/* Light mode support (kalau body punya class light atau tema kamu pakai data-theme="light") */
body.light .pm-shop .pm-shop-panel,
[data-theme="light"] .pm-shop .pm-shop-panel{
  background: rgba(0,0,0,.03);
  border-color: rgba(0,0,0,.08);
}
body.light .pm-shop .pm-card,
[data-theme="light"] .pm-shop .pm-card{
  background: rgba(0,0,0,.03);
  border-color: rgba(0,0,0,.08);
}
body.light .pm-shop .pm-card:hover,
[data-theme="light"] .pm-shop .pm-card:hover{
  background: rgba(0,0,0,.05);
  border-color: rgba(0,0,0,.12);
}
body.light .pm-shop .pm-thumb,
[data-theme="light"] .pm-shop .pm-thumb{
  background: rgba(0,0,0,.03);
  border-color: rgba(0,0,0,.08);
}
body.light .pm-shop .pm-pill,
[data-theme="light"] .pm-shop .pm-pill{
  background: rgba(255,255,255,.70);
  border-color: rgba(0,0,0,.10);
}
body.light .pm-shop .pm-badge-out,
[data-theme="light"] .pm-shop .pm-badge-out{
  background: rgba(0,0,0,.06);
  border-color: rgba(0,0,0,.10);
}
</style>
<?= view('customer/menu', ['func' => $func, 'db' => $db]) ?>
<div class="pm-shop">
  <div class="pm-shop-head">
    <?php if ($cariRaw !== "") { ?>
      <h1 class="pm-shop-title">Hasil Pencarian</h1>
      <div class="pm-shop-sub">Kata kunci: <b><?= htmlspecialchars($cariRaw, ENT_QUOTES, 'UTF-8') ?></b></div>
    <?php } else { ?>
      <h1 class="pm-shop-title">Semua Produk</h1>
      <div class="pm-shop-sub">Produk fisik &amp; jasa, termasuk yang sedang flash sale.</div>
    <?php } ?>
  </div>

  <div class="pm-shop-panel">
    <?php if ($dbResult->getNumRows() === 0) { ?>
      <div class="pm-empty">
        <h3>Produk tidak ditemukan</h3>
        <p>Coba kata kunci lain atau cek ejaan pencarian.</p>
      </div>
    <?php } else { ?>
      <div class="pm-grid">
        <?php foreach ($dbResult->getResult() as $r) {
          $harga = $getPriceByLevel($r);
          $diskon = (int)$r->diskon;
          $hargaAkhir = ($diskon > 0) ? (int)round($harga - ($harga * $diskon / 100)) : $harga;
          $ulasan = $func->getReviewProduk($r->id);

          // stok total (utama + variasi)
          $dbv = $db->table("produkvariasi")->where("idproduk", $r->id)->get();
          $totalstok = ($dbv->getNumRows() > 0) ? 0 : (int)$r->stok;
          foreach ($dbv->getResult() as $rv) $totalstok += (int)$rv->stok;
          $isOut = ($totalstok <= 0);

          $img = $func->getFoto($r->id, "utama");
          $url = site_url('produk/' . $r->url);

          // deskripsi singkat (kalau ada)
          $desc = isset($r->deskripsi) ? strip_tags((string)$r->deskripsi) : "";
          $desc = trim(preg_replace('/\s+/', ' ', $desc));
          if ($desc === "") $desc = "Layanan / Produk";

          // render bintang rating (penuh/kosong) berdasarkan nilai 0-5
          $bintangPenuh = (int)round($ulasan['nilai']);
          $starsHtml = str_repeat('★', $bintangPenuh) . str_repeat('☆', 5 - $bintangPenuh);
        ?>
          <div class="pm-card">
            <?php if ($isOut) { ?><div class="pm-badge-out">Habis</div><?php } ?>
            <?php if ($r->flash == 1) { ?><div class="pm-badge-flash">⚡ Flash Sale</div><?php } ?>
            <?php if ($diskon > 0) { ?><div class="pm-badge-discount"><?= $diskon ?>%</div><?php } ?>
            <a href="<?= $url ?>">
              <div class="pm-row">
                <div class="pm-thumb">
                  <img src="<?= $img ?>" alt="<?= htmlspecialchars($r->nama, ENT_QUOTES, 'UTF-8') ?>" loading="lazy" decoding="async">
                </div>
                <div class="pm-meta">
                  <p class="pm-name"><?= htmlspecialchars($r->nama, ENT_QUOTES, 'UTF-8') ?></p>
                  <div class="pm-desc"><?= htmlspecialchars($desc, ENT_QUOTES, 'UTF-8') ?></div>
                </div>
              </div>

              <div class="pm-rating">
                <span class="pm-rating-score"><?= number_format($ulasan['nilai'], 1) ?></span>
                <span class="pm-rating-stars"><?= $starsHtml ?></span>
              </div>

              <?php if ($diskon > 0) { ?>
                <div class="pm-price-old">Rp <?= $func->formUang($harga) ?></div>
              <?php } ?>
              <div class="pm-price"><?= ($diskon > 0) ? 'Rp ' . $func->formUang($hargaAkhir) : 'Rp ' . $func->formUang($harga) ?></div>
              <div class="pm-ulasan"><?= $ulasan['ulasan'] ?> Ulasan</div>
            </a>
          </div>
        <?php } ?>
      </div>
    <?php } ?>
  </div>

  <div class="pm-pagination pagination justify-content-center">
    <?php
      if ($totalRows > $perpage) {
        echo $func->createPagination($totalRows, $page, $perpage);
      }
    ?>
  </div>
</div>
