<?= view('customer/menu', ['func' => $func, 'db' => $db]) ?>

<main class="wrap">

  <!-- =======================
       FORM NOMOR HP (LEGA)
  ======================== -->
  <div class="ppob-page">
    <div class="ppob-card">
      <div class="ppob-head">
        <div class="ppob-title">Pulsa</div>
        <div class="ppob-subtitle">Masukkan nomor HP untuk menampilkan pilihan nominal.</div>
      </div>

      <form id="formPulsa" method="post" action="javascript:void(0);" autocomplete="off">
        <input type="hidden" id="service_data" value="pulsa">

        <!-- CSRF -->
        <input type="hidden"
               id="csrf_name"
               name="<?= csrf_token(); ?>"
               value="<?= csrf_hash(); ?>">

        <div class="phone-field">
          <div class="phone-icon" aria-hidden="true">
            <!-- phone icon -->
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
              <path d="M16.5 3H7.5C6.67157 3 6 3.67157 6 4.5V19.5C6 20.3284 6.67157 21 7.5 21H16.5C17.3284 21 18 20.3284 18 19.5V4.5C18 3.67157 17.3284 3 16.5 3Z" stroke="currentColor" stroke-width="1.7"/>
              <path d="M10 18.25H14" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
            </svg>
          </div>

          <div class="phone-input-wrap">
            <label class="phone-label" for="phone_data">Nomor HP</label>
            <input
              type="tel"
              inputmode="numeric"
              pattern="[0-9]*"
              id="phone_data"
              name="nomorhp"
              class="phone-input"
              placeholder="Contoh: 081234567890"
              maxlength="16"
              aria-describedby="phone_help provider_help"
            />
            <div class="phone-help" id="phone_help">Gunakan nomor aktif. Format boleh diawali 08 / 62.</div>
          </div>
</div>

        <div class="provider-line">
          <span class="provider-pill" id="provider_help">
            Provider: <b id="provider_text">-</b>
          </span>

          <span class="provider-note" id="provider_note">
            Nominal akan muncul otomatis setelah provider terdeteksi.
          </span>
        </div>
      </form>
    </div>

    <!-- =======================
         HASIL NOMINAL (AJAX)
    ======================== -->
    <div class="ppob-card ppob-card-soft">
      <div class="ppob-title-sm">Pilihan Nominal</div>

      <div id="pesanorder_data" class="ppob-alert ppob-alert-warn" style="display:none;"></div>

      <div id="hasilnominal_data" class="nominal-wrap">
        <div class="nominal-empty">
          Masukkan nomor HP untuk melihat daftar nominal pulsa.
        </div>
      </div>
    </div>

    <!-- kalau Anda butuh area order/hasil lain, tetap saya sediakan id-nya -->
    <div id="hasilorder_data" style="display:none;"></div>
  </div>

</main>

<!-- CSS kartu PPOB (ppob-page, phone-field, nominal-item, dst) sudah global di headtukunen.php -->

<script>
(function(){
  function normalizePhone(raw){
    raw = (raw || '').toString().replace(/[^0-9]/g,'');
    if(raw.startsWith('0')) raw = '62' + raw.slice(1);
    return raw;
  }

  var prefixMap = [
    {brand:'TELKOMSEL', re:/^(62811|62812|62813|62821|62822|62823|62851|62852|62853)/},
    {brand:'INDOSAT',   re:/^(62814|62815|62816|62855|62856|62857|62858)/},
    {brand:'XL',        re:/^(62817|62818|62819|62859|62877|62878)/},
    {brand:'AXIS',      re:/^(62831|62832|62833|62838)/},
    {brand:'TRI',       re:/^(62895|62896|62897|62898|62899)/},
    {brand:'SMARTFREN', re:/^(62881|62882|62883|62884|62885|62886|62887|62888|62889)/}
  ];
  function detectBrand(phone62){
    for(var i=0;i<prefixMap.length;i++){
      if(prefixMap[i].re.test(phone62)) return prefixMap[i].brand;
    }
    return '';
  }

  function setProviderText(txt){
    var el = document.getElementById('provider_text');
    if(el) el.textContent = txt || '-';
  }
  function showWarn(msg){
    var box = document.getElementById('provider_note');
    if(!box) return;
    if(msg){
      box.style.display = '';
      box.textContent = msg;
    }else{
      box.style.display = 'none';
      box.textContent = '';
    }
  }
  function setNominalHtml(html){
    var wrap = document.getElementById('hasilnominal_data');
    if(!wrap) return;
    wrap.innerHTML = html;
  }

  // mapping brand -> key alternatif (kalau server Anda pakai format beda)
  var brandKeyMap = {
    'TELKOMSEL':'telkomsel',
    'INDOSAT':'indosat',
    'XL':'xl',
    'AXIS':'axis',
    'TRI':'tri',
    'SMARTFREN':'smartfren'
  };

  var lastReqKey = '';
  function fetchText(url){
    return fetch(url, {
      credentials:'same-origin',
      headers: { 'X-Requested-With': 'XMLHttpRequest' } // PENTING untuk CI is_ajax_request()
    }).then(function(r){ return r.text(); });
  }

  function loadNominalPulsa(brand){
    if(!brand) return;

    var urlBase = "<?= site_url('ppob/datalistajax/2/'); ?>";

    // coba beberapa pola URL (biar cocok dengan berbagai controller)
    var keyAlt = brandKeyMap[brand] || brand;
    var tries = [
      urlBase + encodeURIComponent(brand),                 // .../2/TELKOMSEL
      urlBase + encodeURIComponent(keyAlt),                // .../2/telkomsel
      urlBase.replace(/\/$/, '') + '?brand=' + encodeURIComponent(brand),   // .../2?brand=TELKOMSEL
      urlBase.replace(/\/$/, '') + '?brand=' + encodeURIComponent(keyAlt)   // .../2?brand=telkomsel
    ];

    var reqKey = brand + '|' + Date.now();
    lastReqKey = reqKey;

    showWarn('');
    setNominalHtml('<div class="ppob-empty">Memuat nominal...</div>');

    // eksekusi berurutan sampai dapat response yang valid
    (function tryNext(i){
      if(i >= tries.length){
        if(lastReqKey !== reqKey) return;
        showWarn('Nominal tidak tersedia / endpoint tidak merespons.');
        setNominalHtml('<div class="ppob-empty">Tidak ada data.</div>');
        return;
      }
      fetchText(tries[i]).then(function(t){
        if(lastReqKey !== reqKey) return;
        // valid minimal: isi lumayan panjang dan bukan halaman 404 umum
        if(t && t.trim().length >= 20 && !/404|not found|error/i.test(t)){
          setNominalHtml(t);
        }else{
          tryNext(i+1);
        }
      }).catch(function(){
        if(lastReqKey !== reqKey) return;
        tryNext(i+1);
      });
    })(0);
  }

  var debounceTimer = null;
  function onPhoneInput(){
    var inp = document.getElementById('phone_data');
    if(!inp) return;

    var n = normalizePhone(inp.value);
    var brand = detectBrand(n);

    setProviderText(brand || '-');

    if(!brand){
      setNominalHtml('<div class="ppob-empty">Masukkan nomor HP untuk melihat daftar nominal pulsa.</div>');
      return;
    }

    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(function(){
      loadNominalPulsa(brand);
    }, 350);
  }

  document.addEventListener('DOMContentLoaded', function(){
    var inp = document.getElementById('phone_data');
    if(inp){
      inp.addEventListener('input', onPhoneInput);
      if(inp.value && inp.value.trim() !== '') onPhoneInput();
    }
  });
})();
</script>
