<?php
// ============================================================
// FILE: produk.php
// Halaman Detail Produk
// Fitur:
//  - Image Slider (thumbnail strip + main view + swipe mobile)
//  - Lightbox zoom
//  - Kalkulator Harga Real-time (input meter → harga otomatis)
//  - Tambah ke Keranjang dengan validasi stok
//  - Tab: Deskripsi / Spesifikasi / Info Pengiriman
//  - Produk Terkait (same kategori)
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/rajaongkir.php';
require_once __DIR__ . '/includes/auth.php';

$pdo  = db();
$slug = trim($_GET['slug'] ?? '');

if (!$slug) { redirect(BASE_URL . '/katalog.php'); }

// ── Ambil produk ─────────────────────────────────────────────
$stmt = $pdo->prepare("
    SELECT p.*, k.nama AS nama_kategori, k.slug AS slug_kategori
    FROM produk p
    JOIN kategori k ON p.kategori_id = k.id
    WHERE p.slug = ? AND p.is_aktif = 1
    LIMIT 1
");
$stmt->execute([$slug]);
$produk = $stmt->fetch();

if (!$produk) { redirect(BASE_URL . '/katalog.php'); }

// ── Foto produk (slider) ─────────────────────────────────────
$stmtFoto = $pdo->prepare("
    SELECT * FROM produk_foto
    WHERE produk_id = ?
    ORDER BY urutan ASC, id ASC
");
$stmtFoto->execute([$produk['id']]);
$fotoList = $stmtFoto->fetchAll();

// Placeholder jika belum ada foto
$fotoPlaceholders = [
    'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=900&q=80',
];

// ── Produk terkait ────────────────────────────────────────────
$stmtTerkait = $pdo->prepare("
    SELECT p.id, p.nama, p.slug, p.harga, p.satuan, p.stok,
           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.kategori_id = ? AND p.id != ? AND p.is_aktif = 1
    ORDER BY RAND()
    LIMIT 4
");
$stmtTerkait->execute([$produk['kategori_id'], $produk['id']]);
$produkTerkait = $stmtTerkait->fetchAll();

// ── Proses POST: tambah ke keranjang ─────────────────────────
$formError = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['aksi_keranjang'])) {
    $langsung = isset($_POST['langsung_checkout']);

    $jumlah = trim($_POST['jumlah'] ?? '1');
    // Izinkan koma desimal (1,5 → 1.5)
    $jumlah = (float) str_replace(',', '.', $jumlah);
    $jumlah = round($jumlah, 2);

    if ($jumlah <= 0) {
        $formError = 'Jumlah harus lebih dari 0.';
    } elseif ((float)$produk['stok'] <= 0) {
        $formError = 'Maaf, stok produk ini sedang habis.';
    } elseif ($jumlah > (float)$produk['stok']) {
        $formError = 'Jumlah melebihi stok tersedia ('
                   . number_format($produk['stok'], 2) . ' ' . $produk['satuan'] . ').';
    } else {
        $sid = session_id();

        // Cek apakah sudah ada di keranjang
        $cek = $pdo->prepare(
            "SELECT id, jumlah FROM keranjang WHERE session_id = ? AND produk_id = ?"
        );
        $cek->execute([$sid, $produk['id']]);
        $existing = $cek->fetch();

        if ($existing) {
            $newJml = min($existing['jumlah'] + $jumlah, (float)$produk['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, $produk['id'], $jumlah]);
        }

        setFlash('success',
            '✓ <strong>' . e($produk['nama']) . '</strong> ('
            . number_format($jumlah, 2) . ' ' . $produk['satuan']
            . ') ditambahkan ke keranjang!'
        );
        if ($langsung) {
            redirect(BASE_URL . '/checkout.php');
        }
        redirect(BASE_URL . '/keranjang.php');
    }
}

// ── Siapkan data foto untuk JS ───────────────────────────────
$fotoUrls = [];
if (!empty($fotoList)) {
    foreach ($fotoList as $f) {
        $fotoUrls[] = UPLOAD_URL . '/produk/' . $f['nama_file'];
    }
} else {
    $fotoUrls = $fotoPlaceholders;
}

// ── Parse spesifikasi (JSON array atau teks biasa) ───────────
$specRows  = null;
$specPlain = '';
if (!empty($produk['spesifikasi'])) {
    $parsed = json_decode($produk['spesifikasi'], true);
    if (is_array($parsed)) {
        $specRows = $parsed;   // [{key:.., value:..}, ...]
    } else {
        $specPlain = $produk['spesifikasi'];
    }
}

$pageTitle  = $produk['nama'];
$activePage = 'katalog';

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

<!-- ── BREADCRUMB ───────────────────────────────────────────── -->
<div class="breadcrumb-bar">
  <div class="container">
    <nav aria-label="breadcrumb">
      <ol class="breadcrumb mb-0 small">
        <li class="breadcrumb-item">
          <a href="<?= BASE_URL ?>"><i class="bi bi-house-door me-1"></i>Beranda</a>
        </li>
        <li class="breadcrumb-item">
          <a href="<?= BASE_URL ?>/katalog.php">Katalog</a>
        </li>
        <li class="breadcrumb-item">
          <a href="<?= BASE_URL ?>/katalog.php?kategori=<?= e($produk['slug_kategori']) ?>">
            <?= e($produk['nama_kategori']) ?>
          </a>
        </li>
        <li class="breadcrumb-item active" aria-current="page">
          <?= e(mb_strlen($produk['nama']) > 40 ? mb_substr($produk['nama'],0,40).'…' : $produk['nama']) ?>
        </li>
      </ol>
    </nav>
  </div>
</div>

<div class="container py-4">

  <?= flashMessage() ?>

  <?php if ($formError): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
      <i class="bi bi-exclamation-triangle-fill me-2"></i><?= $formError ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>

  <!-- ═══════════════════════════════════════════════════════
       BAGIAN 1: SLIDER  +  INFO PRODUK
       ═══════════════════════════════════════════════════════ -->
  <div class="row g-4 g-lg-5 mb-5">

    <!-- ── KOLOM KIRI: Image Slider ── -->
    <div class="col-lg-6">
      <div class="pd-slider-wrap">

        <!-- Foto Utama -->
        <div class="pd-slider-main" id="pdSliderMain"
             data-total="<?= count($fotoUrls) ?>">

          <?php foreach ($fotoUrls as $i => $src): ?>
            <div class="pd-slide <?= $i === 0 ? 'pd-slide--active' : '' ?>"
                 data-index="<?= $i ?>">
              <img src="<?= e($src) ?>"
                   alt="<?= e($produk['nama']) ?> – foto <?= $i+1 ?>"
                   class="pd-slide-img"
                   <?= $i > 0 ? 'loading="lazy"' : '' ?>>
            </div>
          <?php endforeach; ?>

          <!-- Tombol navigasi (muncul hanya jika > 1 foto) -->
          <?php if (count($fotoUrls) > 1): ?>
            <button class="pd-arrow pd-arrow--prev" id="pdPrev" aria-label="Foto sebelumnya">
              <i class="bi bi-chevron-left"></i>
            </button>
            <button class="pd-arrow pd-arrow--next" id="pdNext" aria-label="Foto berikutnya">
              <i class="bi bi-chevron-right"></i>
            </button>

            <!-- Dots -->
            <div class="pd-dots" id="pdDots">
              <?php for ($i = 0; $i < count($fotoUrls); $i++): ?>
                <button class="pd-dot <?= $i===0?'pd-dot--active':'' ?>"
                        data-goto="<?= $i ?>"
                        aria-label="Foto <?= $i+1 ?>"></button>
              <?php endfor; ?>
            </div>
          <?php endif; ?>

          <!-- Tombol zoom -->
          <button class="pd-zoom-btn" id="pdZoomBtn" title="Perbesar foto">
            <i class="bi bi-arrows-fullscreen"></i>
          </button>

          <!-- Counter -->
          <?php if (count($fotoUrls) > 1): ?>
            <div class="pd-counter" id="pdCounter">1 / <?= count($fotoUrls) ?></div>
          <?php endif; ?>
        </div><!-- /pd-slider-main -->

        <!-- Thumbnail Strip -->
        <?php if (count($fotoUrls) > 1): ?>
          <div class="pd-thumbs" id="pdThumbs">
            <?php foreach ($fotoUrls as $i => $src): ?>
              <button class="pd-thumb <?= $i===0?'pd-thumb--active':'' ?>"
                      data-goto="<?= $i ?>"
                      aria-label="Pilih foto <?= $i+1 ?>">
                <img src="<?= e($src) ?>"
                     alt="Thumbnail <?= $i+1 ?>"
                     loading="lazy">
              </button>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>

      </div><!-- /pd-slider-wrap -->
    </div><!-- /kolom kiri -->

    <!-- ── KOLOM KANAN: Info + Kalkulator ── -->
    <div class="col-lg-6">
      <div class="pd-info">

        <!-- Kategori badge -->
        <a href="<?= BASE_URL ?>/katalog.php?kategori=<?= e($produk['slug_kategori']) ?>"
           class="pd-kat-badge">
          <i class="bi bi-tag-fill me-1"></i><?= e($produk['nama_kategori']) ?>
        </a>

        <!-- Nama Produk -->
        <h1 class="pd-nama"><?= e($produk['nama']) ?></h1>

        <!-- Harga -->
        <div class="pd-harga-box">
          <div class="pd-harga-angka"><?= formatRupiah($produk['harga']) ?></div>
          <div class="pd-harga-satuan">per <?= e($produk['satuan']) ?></div>
        </div>

        <!-- Status Stok -->
        <?php
          $stokVal  = (float) $produk['stok'];
          $stokMin  = (float) $produk['stok_minimum'];
          $isHabis  = $stokVal <= 0;
          $isSedikit = !$isHabis && $stokVal <= $stokMin;
        ?>
        <div class="pd-stok-badge <?= $isHabis ? 'pd-stok--habis' : ($isSedikit ? 'pd-stok--sedikit' : 'pd-stok--ada') ?>">
          <?php if ($isHabis): ?>
            <i class="bi bi-x-circle-fill"></i> Stok Habis
          <?php elseif ($isSedikit): ?>
            <i class="bi bi-exclamation-circle-fill"></i>
            Stok Terbatas — Sisa <?= number_format($stokVal, 2) ?> <?= e($produk['satuan']) ?>
          <?php else: ?>
            <i class="bi bi-check-circle-fill"></i>
            Tersedia <?= number_format($stokVal, 2) ?> <?= e($produk['satuan']) ?>
          <?php endif; ?>
        </div>

        <!-- ═══════════════════════════════════════
             KALKULATOR HARGA REAL-TIME
             ═══════════════════════════════════════ -->
        <?php if (!$isHabis): ?>
        <form method="POST" class="pd-kalkulator" id="pdForm"
              novalidate autocomplete="off">
          <input type="hidden" name="aksi_keranjang" value="1">

          <div class="kalk-card">
            <!-- Judul kalkulator -->
            <div class="kalk-title">
              <i class="bi bi-calculator-fill me-2 text-primary"></i>
              Kalkulator Harga
            </div>

            <!-- Input jumlah -->
            <div class="kalk-input-row">
              <label class="kalk-label" for="inputJumlah">
                Jumlah
                <span class="kalk-satuan-hint">(<?= e($produk['satuan']) ?>)</span>
              </label>
              <div class="kalk-qty-group">
                <!-- Tombol minus -->
                <button type="button" class="kalk-qty-btn" id="btnMinus"
                        aria-label="Kurangi">
                  <i class="bi bi-dash-lg"></i>
                </button>

                <!-- Input angka -->
                <input type="number"
                       id="inputJumlah"
                       name="jumlah"
                       class="kalk-qty-input"
                       value="1"
                       min="0.1"
                       max="<?= $stokVal ?>"
                       step="<?= $produk['satuan'] === 'meter' ? '0.1' : '1' ?>"
                       inputmode="decimal"
                       required>

                <!-- Tombol plus -->
                <button type="button" class="kalk-qty-btn" id="btnPlus"
                        aria-label="Tambah">
                  <i class="bi bi-plus-lg"></i>
                </button>

                <!-- Satuan -->
                <span class="kalk-satuan-label"><?= e($produk['satuan']) ?></span>
              </div>
              <div class="kalk-stok-hint">
                Maks: <strong><?= number_format($stokVal, 2) ?> <?= e($produk['satuan']) ?></strong>
              </div>
            </div><!-- /kalk-input-row -->

            <!-- Rincian kalkulasi -->
            <div class="kalk-rincian">
              <div class="kalk-row">
                <span>Harga satuan</span>
                <span><?= formatRupiah($produk['harga']) ?> / <?= e($produk['satuan']) ?></span>
              </div>
              <div class="kalk-row">
                <span>Jumlah</span>
                <span id="kalkDispJumlah">
                  1 <?= e($produk['satuan']) ?>
                </span>
              </div>
              <div class="kalk-row kalk-row--total">
                <span>
                  <strong>Total Harga</strong>
                </span>
                <span class="kalk-total" id="kalkDispTotal">
                  <?= formatRupiah($produk['harga']) ?>
                </span>
              </div>
            </div><!-- /kalk-rincian -->

            <!-- Catatan custom order -->
            <div class="kalk-note">
              <i class="bi bi-lightbulb me-1"></i>
              Butuh ukuran non-standar atau order borongan?
              <a href="<?= BASE_URL ?>/chat.php">Hubungi kami via chat</a>.
            </div>
          </div><!-- /kalk-card -->

          <!-- Tombol Aksi -->
          <div class="pd-action-row">
            <button type="submit" name="aksi_keranjang" value="1"
                    class="btn-tambah-keranjang" id="btnTambah">
              <i class="bi bi-cart-plus-fill me-2"></i>Tambah ke Keranjang
            </button>
          </div>
          <div class="mt-2">
            <button type="submit" name="langsung_checkout" value="1"
                    class="btn-beli-sekarang w-100" id="btnBeli">
              <i class="bi bi-lightning-charge-fill me-2"></i>Beli Sekarang
            </button>
          </div>

        </form><!-- /pd-kalkulator -->

        <!-- ── Widget Cek Ongkir Estimasi ──────────────────── -->
        <div class="pd-ongkir-widget">
          <div class="pd-ongkir-title">
            <i class="bi bi-truck-front-fill"></i>
            Estimasi Ongkos Kirim
            <span class="badge bg-primary-subtle text-primary border border-primary-subtle ms-1" style="font-size:.68rem">
              Dari <?= KOTA_ASAL_NAMA ?>
            </span>
          </div>

          <div class="row g-2 mb-2">
            <div class="col-sm-6">
              <select id="pdProvinsi" class="form-select ck-input" onchange="pdMuatKota(this.value)">
                <option value="">— Pilih Provinsi —</option>
              </select>
            </div>
            <div class="col-sm-6">
              <select id="pdKota" class="form-select ck-input" disabled onchange="pdResetOngkir()">
                <option value="">— Pilih Kota —</option>
              </select>
            </div>
          </div>

          <div class="row g-2 mb-2">
            <div class="col-sm-6">
              <select id="pdKurir" class="form-select ck-input" onchange="pdResetOngkir()">
                <?php foreach (roGetKurirTersedia() as $code => $nama): ?>
                  <option value="<?= $code ?>"><?= $nama ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-sm-6">
              <button type="button" class="btn btn-primary-brand w-100" id="pdBtnCek"
                      onclick="pdCekOngkir()" disabled>
                <i class="bi bi-calculator me-1"></i>Cek Ongkir
              </button>
            </div>
          </div>

          <div id="pdOngkirLoading" class="d-none text-center py-2">
            <span class="spinner-border spinner-border-sm text-primary me-2"></span>
            <small class="text-muted">Menghitung ongkir...</small>
          </div>
          <div id="pdOngkirError" class="alert alert-danger py-2 small d-none mb-0"></div>
          <div id="pdOngkirHasil" class="d-none">
            <div class="small fw-semibold text-muted mb-2">Hasil:</div>
            <div id="pdOngkirList" class="d-flex flex-column gap-2"></div>
            <p class="small text-muted mt-2 mb-0">
              <i class="bi bi-info-circle me-1"></i>
              Ini estimasi saja. Ongkir final dikonfirmasi saat checkout.
            </p>
          </div>
        </div>

        <?php else: /* stok habis */ ?>
          <!-- Produk habis: tampilkan notifikasi + tombol WA -->
          <div class="pd-habis-notice">
            <i class="bi bi-exclamation-triangle-fill fs-3 text-warning d-block mb-2"></i>
            <strong>Stok Sedang Habis</strong>
            <p class="small text-muted mt-1 mb-3">
              Hubungi kami untuk informasi restock atau pemesanan indent.
            </p>
            <a href="<?= BASE_URL ?>/tracking.php" class="btn btn-outline-primary w-100"><i class="bi bi-bell me-2"></i>Hubungi Kami untuk Restock</a>
          </div>
        <?php endif; ?>

        <!-- Info mini (pengiriman, garansi, dll) -->
        <div class="pd-mini-info">
          <div class="pd-mini-item">
            <i class="bi bi-truck text-primary"></i>
            <span>Pengiriman Jabodetabek</span>
          </div>
          <div class="pd-mini-item">
            <i class="bi bi-shield-check text-success"></i>
            <span>Kualitas Bergaransi</span>
          </div>
          <div class="pd-mini-item">
            <i class="bi bi-tools text-warning"></i>
            <span>Tersedia Jasa Pasang</span>
          </div>
          <div class="pd-mini-item">
            <i class="bi bi-headset text-info"></i>
            <span>Konsultasi Gratis</span>
          </div>
        </div>

      </div><!-- /pd-info -->
    </div><!-- /kolom kanan -->

  </div><!-- /row -->

  <!-- ═══════════════════════════════════════════════════════
       BAGIAN 2: TAB DESKRIPSI / SPESIFIKASI / PENGIRIMAN
       ═══════════════════════════════════════════════════════ -->
  <div class="pd-tabs-wrap mb-5">
    <!-- Tab Nav -->
    <ul class="nav pd-tab-nav" id="pdTabNav" role="tablist">
      <li class="nav-item" role="presentation">
        <button class="pd-tab-btn active" data-bs-toggle="tab"
                data-bs-target="#tabDeskripsi" type="button" role="tab">
          <i class="bi bi-card-text me-2"></i>Deskripsi Produk
        </button>
      </li>
      <?php if (!empty($specRows) || !empty($specPlain)): ?>
        <li class="nav-item" role="presentation">
          <button class="pd-tab-btn" data-bs-toggle="tab"
                  data-bs-target="#tabSpesifikasi" type="button" role="tab">
            <i class="bi bi-list-check me-2"></i>Spesifikasi
          </button>
        </li>
      <?php endif; ?>
      <li class="nav-item" role="presentation">
        <button class="pd-tab-btn" data-bs-toggle="tab"
                data-bs-target="#tabPengiriman" type="button" role="tab">
          <i class="bi bi-truck me-2"></i>Pengiriman &amp; Pemasangan
        </button>
      </li>
    </ul>

    <!-- Tab Content -->
    <div class="tab-content pd-tab-content">

      <!-- Tab 1: Deskripsi -->
      <div class="tab-pane fade show active" id="tabDeskripsi" role="tabpanel">
        <div class="pd-deskripsi-text">
          <?= nl2br(e($produk['deskripsi'])) ?>
        </div>
      </div>

      <!-- Tab 2: Spesifikasi -->
      <?php if (!empty($specRows) || !empty($specPlain)): ?>
        <div class="tab-pane fade" id="tabSpesifikasi" role="tabpanel">
          <?php if ($specRows): ?>
            <div class="table-responsive">
              <table class="table table-bordered pd-spec-table">
                <tbody>
                  <?php foreach ($specRows as $row): ?>
                    <tr>
                      <th class="pd-spec-key" width="38%">
                        <?= e($row['key'] ?? $row[0] ?? '') ?>
                      </th>
                      <td><?= e($row['value'] ?? $row[1] ?? '') ?></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php else: ?>
            <div class="pd-deskripsi-text"><?= nl2br(e($specPlain)) ?></div>
          <?php endif; ?>
        </div>
      <?php endif; ?>

      <!-- Tab 3: Pengiriman -->
      <div class="tab-pane fade" id="tabPengiriman" role="tabpanel">
        <div class="row g-3">
          <?php
            $infoPengiriman = [
              ['icon'=>'truck-front-fill',       'warna'=>'primary',   'judul'=>'Pengiriman Reguler',
               'desc'=>'Area Jabodetabek. Biaya ongkir dihitung dari berat & jarak. Estimasi 1–3 hari kerja.'],
              ['icon'=>'lightning-charge-fill',  'warna'=>'warning',   'judul'=>'Same-Day Delivery',
               'desc'=>'Area Bekasi. Pesan sebelum pukul 11.00 WIB, barang tiba di hari yang sama.'],
              ['icon'=>'tools',                  'warna'=>'success',   'judul'=>'Jasa Pemasangan',
               'desc'=>'Tim berpengalaman siap memasang di lokasi Anda. Hubungi kami untuk estimasi biaya.'],
              ['icon'=>'shop',                   'warna'=>'secondary', 'judul'=>'Ambil Sendiri (Pickup)',
               'desc'=>'Silakan datang langsung ke toko kami. Hubungi kami sebelum datang.'],
            ];
          ?>
          <?php foreach ($infoPengiriman as $info): ?>
            <div class="col-md-6">
              <div class="pd-pengiriman-card">
                <div class="pd-pengiriman-icon text-<?= $info['warna'] ?>">
                  <i class="bi bi-<?= $info['icon'] ?>"></i>
                </div>
                <div>
                  <h6 class="mb-1 fw-bold"><?= $info['judul'] ?></h6>
                  <p class="small text-muted mb-0"><?= $info['desc'] ?></p>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

    </div><!-- /tab-content -->
  </div><!-- /pd-tabs-wrap -->

  <!-- ═══════════════════════════════════════════════════════
       BAGIAN 3: PRODUK TERKAIT
       ═══════════════════════════════════════════════════════ -->
  <?php if (!empty($produkTerkait)): ?>
    <div class="pd-terkait">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="pd-terkait-title mb-0">Produk Lainnya di Kategori Ini</h3>
        <a href="<?= BASE_URL ?>/katalog.php?kategori=<?= e($produk['slug_kategori']) ?>"
           class="btn btn-outline-secondary btn-sm">
          Lihat Semua <i class="bi bi-arrow-right ms-1"></i>
        </a>
      </div>
      <div class="row g-3">
        <?php foreach ($produkTerkait as $t):
          $fotoT = $t['foto_utama']
            ? UPLOAD_URL . '/produk/' . e($t['foto_utama'])
            : 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=400&q=70';
          $habisT = (float)$t['stok'] <= 0;
        ?>
          <div class="col-lg-3 col-md-4 col-6">
            <article class="produk-card <?= $habisT ? 'produk-card--habis' : '' ?>">
              <a href="<?= BASE_URL ?>/produk.php?slug=<?= e($t['slug']) ?>"
                 class="produk-img-link" tabindex="-1">
                <div class="produk-img-wrap">
                  <img src="<?= $fotoT ?>" alt="<?= e($t['nama']) ?>"
                       class="produk-img" loading="lazy">
                  <?php if ($habisT): ?>
                    <div class="produk-label produk-label--habis">Stok Habis</div>
                  <?php endif; ?>
                  <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($t['slug']) ?>"
                   class="produk-nama-link">
                  <h3 class="produk-nama"><?= e($t['nama']) ?></h3>
                </a>
                <div class="produk-footer">
                  <div class="produk-harga-wrap">
                    <div class="produk-harga"><?= formatRupiah($t['harga']) ?></div>
                    <div class="produk-satuan">/ <?= e($t['satuan']) ?></div>
                  </div>
                  <a href="<?= BASE_URL ?>/produk.php?slug=<?= e($t['slug']) ?>"
                     class="produk-btn-detail">
                    <i class="bi bi-arrow-right"></i>
                  </a>
                </div>
              </div>
            </article>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
  <?php endif; ?>

</div><!-- /container -->

<!-- ══════════════════════════════════════════════════════════
     LIGHTBOX MODAL
     ══════════════════════════════════════════════════════════ -->
<div id="pdLightbox" class="pd-lightbox" role="dialog" aria-modal="true" aria-label="Foto produk">
  <div class="pd-lightbox-backdrop" id="pdLightboxBackdrop"></div>
  <div class="pd-lightbox-inner">
    <button class="pd-lightbox-close" id="pdLightboxClose" aria-label="Tutup">
      <i class="bi bi-x-lg"></i>
    </button>
    <button class="pd-lightbox-nav pd-lightbox-prev" id="pdLbPrev" aria-label="Sebelumnya">
      <i class="bi bi-chevron-left"></i>
    </button>
    <img src="" alt="Foto produk" class="pd-lightbox-img" id="pdLightboxImg">
    <button class="pd-lightbox-nav pd-lightbox-next" id="pdLbNext" aria-label="Berikutnya">
      <i class="bi bi-chevron-right"></i>
    </button>
    <div class="pd-lightbox-counter" id="pdLbCounter"></div>
  </div>
</div>

<!-- ── DATA UNTUK JAVASCRIPT ────────────────────────────────── -->
<script>
/* ============================================================
   Data produk yang diteruskan dari PHP ke JS
   ============================================================ */
const PD = {
  harga  : <?= (float) $produk['harga'] ?>,
  satuan : <?= json_encode($produk['satuan']) ?>,
  stok   : <?= (float) $produk['stok'] ?>,
  step   : <?= $produk['satuan'] === 'meter' ? 0.1 : 1 ?>,
  fotos  : <?= json_encode($fotoUrls, JSON_UNESCAPED_SLASHES) ?>,
};

/* ============================================================
   FORMAT RUPIAH (client-side)
   ============================================================ */
function formatRp(angka) {
  return 'Rp\u00a0' + Math.round(angka).toLocaleString('id-ID');
}

/* ============================================================
   SLIDER
   ============================================================ */
let currentIdx = 0;

function slideTo(idx) {
  const total  = PD.fotos.length;
  idx = ((idx % total) + total) % total; // loop

  // Slides
  document.querySelectorAll('.pd-slide').forEach((el, i) => {
    el.classList.toggle('pd-slide--active', i === idx);
  });

  // Thumbnails
  document.querySelectorAll('.pd-thumb').forEach((el, i) => {
    el.classList.toggle('pd-thumb--active', i === idx);
    // Auto-scroll thumbnail ke posisi yang terlihat
    if (i === idx) el.scrollIntoView({ behavior: 'smooth', inline: 'nearest', block: 'nearest' });
  });

  // Dots
  document.querySelectorAll('.pd-dot').forEach((el, i) => {
    el.classList.toggle('pd-dot--active', i === idx);
  });

  // Counter
  const counter = document.getElementById('pdCounter');
  if (counter) counter.textContent = (idx + 1) + ' / ' + total;

  currentIdx = idx;
}

/* ── Tombol panah ──────────────────────────────────────────── */
document.getElementById('pdPrev')?.addEventListener('click', () => slideTo(currentIdx - 1));
document.getElementById('pdNext')?.addEventListener('click', () => slideTo(currentIdx + 1));

/* ── Thumbnail klik ────────────────────────────────────────── */
document.querySelectorAll('.pd-thumb, .pd-dot').forEach(btn => {
  btn.addEventListener('click', () => slideTo(+btn.dataset.goto));
});

/* ── Swipe / drag (mobile & desktop) ──────────────────────── */
(function () {
  const el = document.getElementById('pdSliderMain');
  if (!el) return;

  let startX = 0, isDragging = false;

  el.addEventListener('mousedown',  e => { startX = e.clientX; isDragging = true; });
  el.addEventListener('mousemove',  e => { if (!isDragging) return; });
  el.addEventListener('mouseup',    e => {
    if (!isDragging) return;
    isDragging = false;
    const diff = startX - e.clientX;
    if (Math.abs(diff) > 40) slideTo(currentIdx + (diff > 0 ? 1 : -1));
  });
  el.addEventListener('mouseleave', () => { isDragging = false; });

  // Touch
  el.addEventListener('touchstart', e => { startX = e.touches[0].clientX; }, { passive: true });
  el.addEventListener('touchend',   e => {
    const diff = startX - e.changedTouches[0].clientX;
    if (Math.abs(diff) > 40) slideTo(currentIdx + (diff > 0 ? 1 : -1));
  }, { passive: true });
})();

/* ── Keyboard arrow ───────────────────────────────────────── */
document.addEventListener('keydown', e => {
  if (document.getElementById('pdLightbox').classList.contains('pd-lightbox--open')) {
    if (e.key === 'ArrowLeft')  lbGo(currentIdx - 1);
    if (e.key === 'ArrowRight') lbGo(currentIdx + 1);
    if (e.key === 'Escape')     closeLightbox();
  } else {
    if (e.key === 'ArrowLeft')  slideTo(currentIdx - 1);
    if (e.key === 'ArrowRight') slideTo(currentIdx + 1);
  }
});

/* ============================================================
   LIGHTBOX
   ============================================================ */
function openLightbox(idx) {
  const lb = document.getElementById('pdLightbox');
  lb.classList.add('pd-lightbox--open');
  document.body.style.overflow = 'hidden';
  lbGo(idx);
}

function closeLightbox() {
  document.getElementById('pdLightbox').classList.remove('pd-lightbox--open');
  document.body.style.overflow = '';
}

function lbGo(idx) {
  const total = PD.fotos.length;
  idx = ((idx % total) + total) % total;
  document.getElementById('pdLightboxImg').src = PD.fotos[idx];
  const counter = document.getElementById('pdLbCounter');
  if (counter) counter.textContent = (idx + 1) + ' / ' + total;
  currentIdx = idx;
}

document.getElementById('pdZoomBtn')?.addEventListener('click', () => openLightbox(currentIdx));
document.getElementById('pdLightboxClose')?.addEventListener('click', closeLightbox);
document.getElementById('pdLightboxBackdrop')?.addEventListener('click', closeLightbox);
document.getElementById('pdLbPrev')?.addEventListener('click', () => lbGo(currentIdx - 1));
document.getElementById('pdLbNext')?.addEventListener('click', () => lbGo(currentIdx + 1));

/* ============================================================
   KALKULATOR HARGA REAL-TIME
   ============================================================ */
const inputJumlah  = document.getElementById('inputJumlah');
const kalkDispJml  = document.getElementById('kalkDispJumlah');
const kalkDispTotal= document.getElementById('kalkDispTotal');

function hitungHarga() {
  if (!inputJumlah) return;

  let jumlah = parseFloat(inputJumlah.value) || 0;

  // Clamp ke range valid
  jumlah = Math.max(PD.step, Math.min(PD.stok, jumlah));

  // Update tampilan jumlah
  if (kalkDispJml) {
    kalkDispJml.textContent = jumlah.toLocaleString('id-ID', {
      minimumFractionDigits: 0,
      maximumFractionDigits: 2
    }) + ' ' + PD.satuan;
  }

  // Update total
  const total = jumlah * PD.harga;
  if (kalkDispTotal) kalkDispTotal.textContent = formatRp(total);

  // Update link WA dengan jumlah terbaru
  if (btnWa) {
    const nama = encodeURIComponent(document.querySelector('.pd-nama')?.textContent?.trim() || '');
    const teks = encodeURIComponent(
      'Halo Budi Jaya, saya ingin memesan *' +
      (document.querySelector('.pd-nama')?.textContent?.trim() || '') +
      '* sebanyak ' + jumlah + ' ' + PD.satuan +
      ' (total estimasi ' + formatRp(total) + ')'
    );
  }
}

/* Tombol +/- */
document.getElementById('btnMinus')?.addEventListener('click', () => {
  if (!inputJumlah) return;
  const val = parseFloat(inputJumlah.value) || 0;
  inputJumlah.value = Math.max(PD.step, Math.round((val - PD.step) * 100) / 100);
  hitungHarga();
});

document.getElementById('btnPlus')?.addEventListener('click', () => {
  if (!inputJumlah) return;
  const val = parseFloat(inputJumlah.value) || 0;
  inputJumlah.value = Math.min(PD.stok, Math.round((val + PD.step) * 100) / 100);
  hitungHarga();
});

/* Real-time saat ketik */
inputJumlah?.addEventListener('input', hitungHarga);
inputJumlah?.addEventListener('change', () => {
  // Koreksi jika di luar range saat blur
  let val = parseFloat(inputJumlah.value) || PD.step;
  val = Math.max(PD.step, Math.min(PD.stok, Math.round(val * 100) / 100));
  inputJumlah.value = val;
  hitungHarga();
});

/* Validasi submit */
document.getElementById('pdForm')?.addEventListener('submit', e => {
  const val = parseFloat(inputJumlah?.value) || 0;
  if (val <= 0) {
    e.preventDefault();
    inputJumlah?.focus();
    alert('Masukkan jumlah yang valid (lebih dari 0).');
  } else if (val > PD.stok) {
    e.preventDefault();
    inputJumlah?.focus();
    alert('Jumlah melebihi stok tersedia (' + PD.stok + ' ' + PD.satuan + ').');
  }
});

/* Init */
document.addEventListener('DOMContentLoaded', hitungHarga);
</script>


<script>
// ── Ongkir Widget — Halaman Produk ───────────────────────────
const PD_BASE  = '<?= BASE_URL ?>';
const PD_BERAT = <?= max(1, (int)round(($produk['berat_per_m'] ?? 1) * 1000)) ?>; // gram per unit
const fmt2 = n => 'Rp ' + parseInt(n).toLocaleString('id-ID');

window.addEventListener('DOMContentLoaded', () => {
  fetch(PD_BASE + '/ongkir.php?action=provinsi')
    .then(r => r.json())
    .then(res => {
      if (!res.success) return;
      const sel = document.getElementById('pdProvinsi');
      res.data.forEach(p => {
        const o = document.createElement('option');
        o.value = p.province_id; o.text = p.province;
        sel.appendChild(o);
      });
    });
});

function pdMuatKota(provId) {
  const selKota = document.getElementById('pdKota');
  const btnCek  = document.getElementById('pdBtnCek');
  selKota.innerHTML = '<option value="">Memuat...</option>';
  selKota.disabled  = true;
  btnCek.disabled   = true;
  pdResetOngkir();
  if (!provId) { selKota.innerHTML = '<option value="">— Pilih Kota —</option>'; return; }
  fetch(PD_BASE + '/ongkir.php?action=kota&provinsi=' + provId)
    .then(r => r.json())
    .then(res => {
      selKota.innerHTML = '<option value="">— Pilih Kota —</option>';
      if (res.success) {
        res.data.forEach(k => {
          const o = document.createElement('option');
          o.value = k.city_id; o.text = k.type + ' ' + k.city_name;
          selKota.appendChild(o);
        });
        selKota.disabled = false;
        selKota.addEventListener('change', () => { btnCek.disabled = !selKota.value; });
      }
    });
}

function pdResetOngkir() {
  document.getElementById('pdOngkirHasil').classList.add('d-none');
  document.getElementById('pdOngkirError').classList.add('d-none');
}

function pdCekOngkir() {
  const kotaId = document.getElementById('pdKota').value;
  const kurir  = document.getElementById('pdKurir').value;
  if (!kotaId) { alert('Pilih kota tujuan dulu.'); return; }

  // Ambil jumlah dari kalkulator jika ada
  const inputJml = document.getElementById('iJumlah');
  const jumlah   = inputJml ? parseFloat(inputJml.value) || 1 : 1;
  const berat    = Math.max(1, Math.round(PD_BERAT * jumlah));

  document.getElementById('pdOngkirLoading').classList.remove('d-none');
  document.getElementById('pdOngkirHasil').classList.add('d-none');
  document.getElementById('pdOngkirError').classList.add('d-none');

  const fd = new FormData();
  fd.append('action', 'cek'); fd.append('kota_id', kotaId);
  fd.append('berat',  berat); fd.append('kurir', kurir);

  fetch(PD_BASE + '/ongkir.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(res => {
      document.getElementById('pdOngkirLoading').classList.add('d-none');
      if (!res.success || !res.services?.length) {
        const errEl = document.getElementById('pdOngkirError');
        errEl.textContent = res.error || 'Tidak ada layanan untuk rute ini.';
        errEl.classList.remove('d-none');
        return;
      }
      const list = document.getElementById('pdOngkirList');
      list.innerHTML = '';
      res.services.forEach(s => {
        const div = document.createElement('div');
        div.className = 'ck-ongkir-card';
        div.style.cursor = 'default';
        div.innerHTML = `
          <div class="ck-ongkir-card-inner">
            <div>
              <span class="ck-ongkir-badge">${s.kurir}</span>
              <strong class="ms-2">${s.service}</strong>
              <span class="text-muted small ms-1">— ${s.description}</span>
            </div>
            <div class="text-end">
              <div class="fw-bold text-primary">${fmt2(s.cost)}</div>
              <div class="text-muted" style="font-size:.75rem">Est. ${s.etd}</div>
            </div>
          </div>`;
        list.appendChild(div);
      });
      document.getElementById('pdOngkirHasil').classList.remove('d-none');
    })
    .catch(() => {
      document.getElementById('pdOngkirLoading').classList.add('d-none');
      const errEl = document.getElementById('pdOngkirError');
      errEl.textContent = 'Gagal menghubungi server ongkir.';
      errEl.classList.remove('d-none');
    });
}
</script>

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