<!-- ================= TOAST ================= -->
<div class="toast" id="toast">Toast</div>

<!-- ================= MODAL: INPUT/CHECKOUT ================= -->
<div class="pm-overlay" id="pmOverlay" aria-hidden="true">
  <div class="pm-box" role="dialog" aria-modal="true" aria-labelledby="pmTitle">
    <div class="pm-head">
      <div>
        <b id="pmTitle">Pulsa</b>
        <div class="muted" id="pmHint" style="font-size:12px;margin-top:2px">Masukkan nomor / ID pelanggan</div>
      </div>
      <button class="btn-icon" type="button" id="pmClose" aria-label="Tutup">✕</button>
    </div>
    <div class="pm-body">
      <div class="note" id="pmProductLine" style="margin-top:0;margin-bottom:10px;display:none;"></div>
      <input class="pm-input" id="pmInput" placeholder="Masukkan nomor / ID" inputmode="numeric">
      <div class="note">Contoh: 0812xxxx / ID Pelanggan</div>
    </div>
    <div class="pm-actions">
      <button class="btn btn-ghost" type="button" id="pmCancel">Batal</button>
      <button class="btn btn-primary" type="button" id="pmNext">Lanjut</button>
    </div>
  </div>
</div>

<!-- ================= MODAL: LOGIN ================= -->
<div class="pm-overlay" id="loginOverlay" aria-hidden="true">
  <div class="pm-box" role="dialog" aria-modal="true" aria-labelledby="loginTitle">
    <div class="pm-head">
      <div>
        <b id="loginTitle">Login</b>
        <div class="muted" style="font-size:12px;margin-top:2px">Masuk untuk akses menu admin / transaksi</div>
      </div>
      <button class="btn-icon" type="button" id="loginClose" aria-label="Tutup">✕</button>
    </div>

    <form method="post" action="<?= site_url('home/signin') ?>" id="pmLoginForm">
  <input type="hidden"
         name="<?= csrf_token(); ?>"
         value="<?= csrf_hash(); ?>">

  <div class="pm-body">
    <div class="field">
      <div class="label">Username</div>
      <input class="pm-input" name="email" id="loginUser" placeholder="Masukkan username" autocomplete="username">
    </div>

    <div class="field" style="margin-bottom:0">
      <div class="label">Password</div>
      <input class="pm-input" type="password" name="pass" id="loginPass" placeholder="Masukkan password" autocomplete="current-password">
    </div>

    <div class="note" style="margin-top:10px">
      Belum punya akun? <a class="link-strong" href="<?= site_url('home/signup') ?>">Daftar sekarang</a>
    </div>
    <div class="note">Tekan <b>ESC</b> untuk menutup pop-up.</div>
  </div>

  <div class="pm-actions">
    <button class="btn btn-ghost" type="button" id="loginCancel">Batal</button>
    <button class="btn btn-primary" type="submit" id="loginSubmit">Masuk</button>
  </div>
</form>

  </div>
</div>

<!-- ================= MOBILE BOTTOM NAV ================= -->
<nav class="mnav" aria-label="Menu Bawah (Mobile)">
  <div class="mnav-inner">
    <a class="mnav-btn" href="<?= base_url() ?>" data-nav="home" aria-label="Beranda">
      <svg viewBox="0 0 24 24"><path d="M12 3l9 8v10a1 1 0 0 1-1 1h-6v-7H10v7H4a1 1 0 0 1-1-1V11l9-8z"/></svg>
    </a>
    <a class="mnav-btn" href="<?= site_url('ppob/kategori') ?>" data-nav="kategori" aria-label="Semua Kategori">
      <svg viewBox="0 0 24 24"><path d="M3 3h8v8H3V3zm10 0h8v8h-8V3zM3 13h8v8H3v-8zm10 0h8v8h-8v-8z"/></svg>
    </a>
    <a class="mnav-center" href="<?= site_url('shop') ?>" data-nav="produk" aria-label="Semua Produk">
      <svg viewBox="0 0 24 24"><path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zm10 0c-1.1 0-1.99.9-1.99 2S15.9 22 17 22s2-.9 2-2-.9-2-2-2zM7.2 14h9.9c.8 0 1.5-.5 1.8-1.2l3-6.6A1 1 0 0 0 21 5H6.3L5.9 3.6A1 1 0 0 0 5 3H2v2h2.2l2.9 10.2c.2.8 1 1.3 1.8 1.3z"/></svg>
    </a>
    <a class="mnav-btn" href="<?= site_url('manage/historidigital') ?>" data-nav="histori" aria-label="Histori Transaksi">
      <svg viewBox="0 0 24 24"><path d="M13 3a9 9 0 0 0-9 9H1l3.9 4 4.1-4H6a7 7 0 1 1 2 4.9l-1.4 1.4A9 9 0 1 0 13 3zm-1 5v5l4 2 .8-1.5L13 12V8h-1z"/></svg>
    </a>
    <button class="mnav-btn" type="button" id="mAkunBtn" data-nav="akun" aria-label="Akun/Profil">
      <svg viewBox="0 0 24 24"><path d="M12 12a4 4 0 1 0-4-4 4 4 0 0 0 4 4zm0 2c-4.4 0-8 2-8 4.5V21h16v-2.5c0-2.5-3.6-4.5-8-4.5z"/></svg>
    </button>
  </div>
</nav>

<footer class="footer-mega">
  <div class="inner">
    <div class="footer-grid">

      <!-- Kontak Kami -->
      <?php $set = $func->getSetting("semua"); ?>
      <div>
        <div class="f-title">Kontak Kami</div>
        <div class="f-links">
          <a href="https://wa.me/<?= $set->wasap ?>" target="_blank" rel="noopener">WhatsApp: <?= $set->wasap ?></a>
          <a href="mailto:<?= $set->email ?>">Email: <?= $set->email ?></a>
          <a href="#">Alamat: <?= $set->alamat ?></a>
          <a href="#"><?= $set->jamkerja ?></a>
        </div>
      </div>

      <!-- Jelajahi Halaman -->
      <div>
        <div class="f-title">Jelajahi Halaman</div>
        <div class="f-links">
                    <a href="<?= site_url("ppob/pricelist") ?>">
                            Pricelist Harga
                        </a>
                    <?php
                    $kategori = $db->table("page")->get();
                    foreach ($kategori->getResult() as $r) {
                    ?>
                        <a href="<?= site_url("page/" . $r->slug) ?>"><?= ucwords(strtolower($r->nama)) ?></a>
                    <?php } ?>
        </div>
      </div>

      <!-- Kategori -->
      <div>
        <div class="f-title">Kategori</div>
        <div class="f-badges">

            <?php
                    $kategori = $db->table("kategori")->where("parent", 0)->limit(8)->get();
                    foreach ($kategori->getResult() as $r) {
                    ?>
                        <a class="badge-chip" href="<?= site_url("kategori/" . $r->url) ?>"><?= ucwords(strtolower($r->nama)) ?></a>
                    <?php
                    }
                    ?>
        </div>
      </div>

      <!-- Download Aplikasi -->
      <div>
        <div class="f-title">Download Aplikasi</div>
        <div class="f-app">
            <?php $playstore = $func->getSetting("playstore");
		    if ($playstore !== "") { ?>

          <div class="store-btns">
            <!-- GANTI href ke link Google Play kamu -->
            <a class="store-btn" href="<?php echo ($playstore); ?>" target="_blank" rel="noopener">
              <img src="<?= base_url('/assets/images/playstore.png') ?>" alt="googleplay download" class="mw-100">
            </a>
          </div>
          <?php } ?>
        </div>
      </div>

    </div>
  </div>

  <div class="footer-bottom">
    <div>© <?= date('Y') ?> <?= strtoupper(strtolower($set->nama)) ?></div>
    <div>PPOB • Digital • Minimarket</div>
  </div>
</footer>

<script>
(function(){

  /* ===== THEME TOGGLE ===== */
  var html = document.documentElement;
  var themeToggle = document.getElementById('themeToggle');
  function applyTheme(t){
    html.setAttribute('data-theme', t);
    try{ localStorage.setItem('pm_theme', t); }catch(e){}
    if(themeToggle) themeToggle.textContent = (t === 'dark') ? '☀️' : '🌙';
  }
  applyTheme(html.getAttribute('data-theme') || 'light');
  if(themeToggle){
    themeToggle.addEventListener('click', function(e){
      e.preventDefault();
      var cur = html.getAttribute('data-theme') || 'light';
      applyTheme(cur === 'dark' ? 'light' : 'dark');
    });
  }

  /* ===== TOAST ===== */
  var toastEl = document.getElementById('toast');
  var toastTimer = null;
  function toast(msg){
    if(!toastEl) return;
    toastEl.textContent = msg;
    toastEl.classList.add('show');
    clearTimeout(toastTimer);
    toastTimer = setTimeout(function(){ toastEl.classList.remove('show'); }, 1400);
  }

  /* ===== MODAL: SERVICE (CEK NOMOR / INPUT ID) ===== */
  var overlay = document.getElementById('pmOverlay');
  var pmTitle = document.getElementById('pmTitle');
  var pmInput = document.getElementById('pmInput');
  var pmHint  = document.getElementById('pmHint');
  var pmProductLine = document.getElementById('pmProductLine');

  function openServiceModal(serviceName, productName, productPrice){
    if(!overlay) return;
    var hints = {
      "Pulsa":"Masukkan nomor HP","Paket Data":"Masukkan nomor HP",
      "Token PLN":"Masukkan ID Pelanggan / No Meter","BPJS":"Masukkan nomor VA / ID peserta",
      "E-Money":"Masukkan nomor / ID e-wallet","Games":"Masukkan ID game / User ID",
      "Voucher":"Masukkan kode/nomor tujuan","Transfer Bank":"Masukkan nomor rekening",
      "PDAM":"Masukkan ID pelanggan","Internet":"Masukkan ID pelanggan","Bank":"Masukkan nomor rekening"
    };
    if(pmTitle) pmTitle.textContent = serviceName || "Layanan";
    if(pmHint) pmHint.textContent = hints[serviceName] || "Masukkan nomor / ID pelanggan";
    if(pmProductLine){
      if(productName){
        pmProductLine.style.display = 'block';
        pmProductLine.textContent = "Produk: " + productName + (productPrice ? " • " + productPrice : "");
      }else{
        pmProductLine.style.display = 'none';
        pmProductLine.textContent = '';
      }
    }
    overlay.classList.add('show');
    overlay.setAttribute('aria-hidden','false');
    if(pmInput) setTimeout(function(){ pmInput.focus(); }, 60);
  }
  function closeServiceModal(){
    if(!overlay) return;
    overlay.classList.remove('show');
    overlay.setAttribute('aria-hidden','true');
    if(pmInput) pmInput.value = "";
    if(pmProductLine){ pmProductLine.style.display = 'none'; pmProductLine.textContent = ''; }
  }
  var pmClose = document.getElementById('pmClose');
  var pmCancel = document.getElementById('pmCancel');
  if(pmClose) pmClose.addEventListener('click', closeServiceModal);
  if(pmCancel) pmCancel.addEventListener('click', closeServiceModal);
  if(overlay) overlay.addEventListener('click', function(e){ if(e.target === overlay) closeServiceModal(); });

  /* ===== MODAL: LOGIN ===== */
  var loginOverlay = document.getElementById('loginOverlay');
  var loginForm = document.getElementById('pmLoginForm');
  var loginUser = document.getElementById('loginUser');
  var loginSubmit = document.getElementById('loginSubmit');

  function openLogin(){
    if(!loginOverlay) return;
    loginOverlay.classList.add('show');
    loginOverlay.setAttribute('aria-hidden','false');
    if(loginUser) setTimeout(function(){ loginUser.focus(); }, 60);
  }
  function closeLogin(){
    if(!loginOverlay) return;
    loginOverlay.classList.remove('show');
    loginOverlay.setAttribute('aria-hidden','true');
  }
  document.querySelectorAll('[data-open="login"], #btnLogin').forEach(function(el){
    el.addEventListener('click', function(e){ e.preventDefault(); openLogin(); });
  });
  var loginClose = document.getElementById('loginClose');
  var loginCancel = document.getElementById('loginCancel');
  if(loginClose) loginClose.addEventListener('click', closeLogin);
  if(loginCancel) loginCancel.addEventListener('click', closeLogin);
  if(loginOverlay){
    loginOverlay.addEventListener('click', function(e){ if(e.target === loginOverlay) closeLogin(); });
  }

  document.addEventListener('keydown', function(e){
    if(e.key !== 'Escape') return;
    closeServiceModal();
    closeLogin();
  });

  if(loginForm){
    loginForm.addEventListener('submit', function(e){
      e.preventDefault();
      if(loginSubmit){ loginSubmit.disabled = true; loginSubmit.textContent = 'Memproses...'; }

      fetch(loginForm.action, {
        method: 'POST',
        body: new FormData(loginForm),
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      })
      .then(function(res){ return res.json(); })
      .then(function(data){
        if(data.csrf){
          var csrfInput = loginForm.querySelector('input[name="<?= csrf_token(); ?>"]');
          if(csrfInput) csrfInput.value = data.csrf;
        }
        if(data.success){
          closeLogin();
          window.location.href = data.redirect || "<?= site_url() ?>";
        }else{
          alert(data.message || 'Username/No HP atau password salah.');
        }
      })
      .catch(function(){
        alert('Gagal login. Cek koneksi / server.');
      })
      .finally(function(){
        if(loginSubmit){ loginSubmit.disabled = false; loginSubmit.textContent = 'Masuk'; }
      });
    });
  }

  /* ===== LOGOUT ===== */
  var btnLogout = document.getElementById('btnLogout');
  if(btnLogout){
    btnLogout.addEventListener('click', function(e){
      e.preventDefault();
      if(!confirm('Yakin ingin keluar?')) return;
      window.location.href = "<?= site_url('home/signout') ?>";
    });
  }

  /* ===== KATEGORI / LAYANAN (svc) - biarkan link asli berjalan ===== */
  document.querySelectorAll('.svc').forEach(function(el){
    el.addEventListener('click', function(){
      document.querySelectorAll('.svc').forEach(function(x){ x.classList.remove('active'); });
      el.classList.add('active');
    });
  });

  /* ===== MOBILE BOTTOM NAV ===== */
  var mAkunBtn = document.getElementById('mAkunBtn');
  if(mAkunBtn){
    mAkunBtn.addEventListener('click', function(){
      var btnLoginEl = document.getElementById('btnLogin');
      if(btnLoginEl){ openLogin(); }
      else{ window.location.href = "<?= site_url('manage') ?>"; }
    });
  }

  /* tandai menu aktif sesuai halaman saat ini */
  (function(){
    var path = window.location.pathname.replace(/\/+$/, '');
    var shopPath = '<?= site_url('shop') ?>'.replace(/^https?:\/\/[^\/]+/, '').replace(/\/+$/, '');
    var kategoriPath = '<?= site_url('ppob/kategori') ?>'.replace(/^https?:\/\/[^\/]+/, '').replace(/\/+$/, '');
    var managePath = '<?= site_url('manage') ?>'.replace(/^https?:\/\/[^\/]+/, '').replace(/\/+$/, '');
    var active = 'home';
    if(path === shopPath){
      active = 'produk';
    }else if(path === kategoriPath){
      active = 'kategori';
    }else if(path.indexOf(managePath) === 0){
      active = (path.indexOf('pesanan') !== -1) ? 'histori' : 'akun';
    }
    document.querySelectorAll('.mnav-btn').forEach(function(b){
      b.classList.toggle('active', b.dataset.nav === active);
    });
  })();

  /* ===== ICON BAR DRAG-SCROLL (svcList) ===== */
  var svcBar = document.getElementById('svcList');
  if(svcBar){
    var isDown = false, startX = 0, startLeft = 0;
    svcBar.addEventListener('mousedown', function(e){
      isDown = true;
      startX = e.pageX;
      startLeft = svcBar.scrollLeft;
      svcBar.style.cursor = 'grabbing';
    });
    window.addEventListener('mouseup', function(){
      isDown = false;
      svcBar.style.cursor = 'grab';
    });
    window.addEventListener('mousemove', function(e){
      if(!isDown) return;
      svcBar.scrollLeft = startLeft - (e.pageX - startX);
    });
    svcBar.style.cursor = 'grab';
  }

  /* ===== SHOP RATING STARS ===== */
  function renderStars(el){
    var rating = parseFloat(el.getAttribute('data-rating') || '0');
    if (isNaN(rating)) rating = 0;
    var full = Math.floor(rating);
    var half = (rating - full) >= 0.5 ? 1 : 0;
    var empty = 5 - full - half;
    var out = '';
    for (var i=0;i<full;i++) out += '<span class="s full">★</span>';
    if (half) out += '<span class="s half">★</span>';
    for (var j=0;j<empty;j++) out += '<span class="s">★</span>';
    el.innerHTML = out;
  }
  document.querySelectorAll('.shop-page .p-stars[data-rating]').forEach(renderStars);

  /* ===== NOMINAL TABS (kategori nominal PPOB, konten dimuat via AJAX) ===== */
  document.addEventListener('click', function(e){
    var tab = e.target.closest ? e.target.closest('.nominal-tab') : null;
    if(!tab) return;
    var wrap = tab.closest('.nominal-wrap, .nominal-tabs-wrap') || tab.parentElement;
    if(!wrap) return;

    var target = tab.getAttribute('data-target');
    if(!target) return;

    wrap.querySelectorAll('.nominal-tab').forEach(function(t){ t.classList.remove('active'); });
    tab.classList.add('active');

    wrap.querySelectorAll('.nominal-panel').forEach(function(p){
      p.classList.toggle('active', p.id === target);
    });
  });

  /* ===== NOMOR HP / DETEKSI OPERATOR (halaman cek pulsa/token/signup) ===== */
  var nohpInput = document.getElementById('nohp');
  var btnCek = document.getElementById('btnCek');
  if(nohpInput){
    var OP_PREFIX = {
      "62811":"Telkomsel","62812":"Telkomsel","62813":"Telkomsel","62821":"Telkomsel","62822":"Telkomsel","62823":"Telkomsel","62851":"Telkomsel","62852":"Telkomsel","62853":"Telkomsel",
      "62814":"Indosat","62815":"Indosat","62816":"Indosat","62855":"Indosat","62856":"Indosat","62857":"Indosat","62858":"Indosat",
      "62817":"XL","62818":"XL","62819":"XL","62859":"XL","62877":"XL","62878":"XL",
      "62831":"AXIS","62832":"AXIS","62833":"AXIS","62838":"AXIS",
      "62895":"Tri","62896":"Tri","62897":"Tri","62898":"Tri","62899":"Tri",
      "62881":"Smartfren","62882":"Smartfren","62883":"Smartfren","62884":"Smartfren","62885":"Smartfren","62886":"Smartfren","62887":"Smartfren","62888":"Smartfren","62889":"Smartfren"
    };
    function normalizePhone(raw){
      if(!raw) return "";
      var s = String(raw).trim().replace(/[\s\.\-\(\)]/g, "");
      if(s.indexOf("+") === 0) s = s.slice(1);
      if(s.indexOf("08") === 0) s = "62" + s.slice(1);
      return s;
    }
    function detectOperator(nohp62){
      if(!nohp62 || nohp62.length < 6) return "";
      return OP_PREFIX[nohp62.slice(0,5)] || "";
    }
    function setOperatorUI(op){
      var pill = document.getElementById("operatorPill");
      var name = document.getElementById("operatorName");
      var opText = document.getElementById("operatorText");
      var opHidden = document.getElementById("operatorHidden");
      if(op){
        if(pill) pill.classList.remove("pm-unknown");
        if(name) name.textContent = op;
        if(opText) opText.textContent = op;
        if(opHidden) opHidden.value = op;
      }else{
        if(pill) pill.classList.add("pm-unknown");
        if(name) name.textContent = "Operator";
        if(opText) opText.textContent = "-";
        if(opHidden) opHidden.value = "";
      }
    }
    function setNoHpUI(nohp62){
      var t = document.getElementById("nohp62Text");
      var hid = document.getElementById("nohp62Hidden");
      if(t) t.textContent = nohp62 || "-";
      if(hid) hid.value = nohp62 || "";
    }
    function refreshDetect(){
      var nohp62 = normalizePhone(nohpInput.value);
      setNoHpUI(nohp62);
      setOperatorUI(detectOperator(nohp62));
      return { nohp62: nohp62 };
    }
    nohpInput.addEventListener("input", refreshDetect);
    nohpInput.addEventListener("blur", refreshDetect);
    if(btnCek){
      btnCek.addEventListener("click", function(){
        var r = refreshDetect();
        if(!r.nohp62 || r.nohp62.length < 10){
          alert("Nomor HP belum valid. Contoh: 0813xxxxxxx");
        }
      });
    }
    refreshDetect();
  }

})();
</script>

</html>
