<?php
// index.php - Simple responsive UI for OrderKuota API demo
?><!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>OrderKuota Web Client</title>
  <style>
    :root{
      --bg:#0b1220;
      --card:#121a2b;
      --muted:#93a1b1;
      --text:#e5ecf4;
      --accent:#7c9cff;
      --accent-2:#4de2b1;
      --danger:#ff6b6b;
      --shadow: 0 10px 30px rgba(0,0,0,.25);
      --radius: 18px;
    }
    *{box-sizing:border-box}
    body{
      margin:0;
      font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
      background: radial-gradient(1000px 600px at 20% -10%, rgba(124,156,255,.15), transparent 60%),
                  radial-gradient(900px 500px at 100% 10%, rgba(77,226,177,.08), transparent 60%),
                  var(--bg);
      color:var(--text);
      min-height:100dvh;
      display:flex;
      flex-direction:column;
    }
    header{
      padding: 28px 20px;
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:16px;
    }
    .brand{
      display:flex; align-items:center; gap:12px; font-weight:700; letter-spacing:.3px;
    }
    .brand .logo{
      width:40px;height:40px;border-radius:12px; background: linear-gradient(135deg, var(--accent), var(--accent-2));
      box-shadow: var(--shadow);
    }
    .container{
      width:100%; max-width:1100px; margin:0 auto; padding: 0 16px 60px;
      flex:1;
    }
    .grid{
      display:grid; grid-template-columns: repeat(12, 1fr); gap:18px;
    }
    .card{
      grid-column: span 12;
      background: rgba(255,255,255,.02);
      border: 1px solid rgba(124,156,255,.15);
      border-radius: var(--radius);
      box-shadow: var(--shadow);
      overflow:hidden;
      backdrop-filter: blur(6px);
    }
    .card-header{ padding: 18px 18px 0; }
    .card-title{ margin:0; font-size: 18px; }
    .card-body{ padding: 18px; display:grid; gap:12px; }
    label{ font-size:13px; color: var(--muted); display:block; margin-bottom:6px;}
    input{
      width:100%; padding:12px 14px; border-radius:12px; border:1px solid rgba(255,255,255,.12);
      background: rgba(12,18,32,.8); color: var(--text);
      outline: none;
    }
    input::placeholder{ color: #8ea0b3; }
    .row{ display:grid; grid-template-columns: 1fr 1fr; gap:12px;}
    .actions{ display:flex; gap:10px; flex-wrap:wrap; }
    button{
      padding: 12px 16px; border-radius: 999px; border: 1px solid rgba(255,255,255,.18);
      background: linear-gradient(135deg, rgba(124,156,255,.2), rgba(124,156,255,.05));
      color: var(--text); cursor:pointer; font-weight:600; letter-spacing:.3px;
      transition: transform .12s ease, background .2s ease;
    }
    button:hover{ transform: translateY(-1px); background: linear-gradient(135deg, rgba(124,156,255,.25), rgba(124,156,255,.08)); }
    .btn-danger{ background: linear-gradient(135deg, rgba(255,107,107,.2), rgba(255,107,107,.05)); }
    .pill{
      font-size:12px; padding:6px 10px; border-radius:999px; background: rgba(77,226,177,.18); color: #c9ffee; border: 1px solid rgba(77,226,177,.35);
    }
    pre{
      margin:0; padding:16px; max-height:260px; overflow:auto; background: #0b1322; border-top:1px solid rgba(255,255,255,.08);
      font-size: 12px; line-height:1.5; border-bottom-left-radius: var(--radius); border-bottom-right-radius: var(--radius);
    }
    .kbd{ font-size: 12px; padding:2px 6px; border:1px solid rgba(255,255,255,.2); border-bottom-width:2px; border-radius:6px; }
    .footer{ color: var(--muted); font-size: 12px; text-align:center; padding: 20px; }
    @media (min-width: 900px){
      .card.span-6{ grid-column: span 6; }
      .card.span-4{ grid-column: span 4; }
    }
  </style>
</head>
<header class="container">
  <div class="brand">
    <div class="logo"></div>
    <div>
      <div>OrderKuota Web Client</div>
      <div class="pill">Demo • PHP + Fetch API</div>
    </div>
  </div>
  <div class="actions">
    <a href="history">
      <button id="btnHistory" title="Lihat riwayat transaksi QRIS">Riwayat Qris</button>
    </a>
    <button id="clearState" class="btn-danger" title="Hapus data tersimpan">Hapus Data Lokal</button>
  </div>
</header>


  <main class="container">
    <div class="grid">

      <section class="card span-6">
        <div class="card-header">
          <h3 class="card-title">1) Login Request <span class="pill">minta OTP</span></h3>
        </div>
        <div class="card-body">
          <div class="row">
            <div>
              <label>Username</label>
              <input id="lr_username" placeholder="mis. 08xxxxxxxxxx" autocomplete="username">
            </div>
            <div>
              <label>Password</label>
              <input id="lr_password" type="password" placeholder="password akun" autocomplete="current-password">
            </div>
          </div>
          <div class="actions">
            <button id="btnLoginRequest">Kirim Login Request</button>
          </div>
        </div>
        <pre id="lr_result">// Hasil loginRequest muncul di sini</pre>
      </section>

      <section class="card span-6">
        <div class="card-header">
          <h3 class="card-title">2) Get Auth Token <span class="pill">verifikasi OTP</span></h3>
        </div>
        <div class="card-body">
          <div class="row">
            <div>
              <label>Username</label>
              <input id="ga_username" placeholder="username yang sama" autocomplete="username">
            </div>
            <div>
              <label>OTP</label>
              <input id="ga_otp" placeholder="kode OTP dari OrderKuota" inputmode="numeric" autocomplete="one-time-code">
            </div>
          </div>
          <div class="actions">
            <button id="btnGetAuthToken">Ambil Auth Token</button>
          </div>
        </div>
        <pre id="ga_result">// Hasil getAuthToken muncul di sini</pre>
      </section>

      <section class="card span-6">
        <div class="card-header">
          <h3 class="card-title">3) Get Transaction QRIS</h3>
        </div>
        <div class="card-body">
          <div class="row">
            <div>
              <label>Username</label>
              <input id="gt_username" placeholder="username" autocomplete="username">
            </div>
            <div>
              <label>Auth Token</label>
              <input id="gt_token" placeholder="paste auth token" autocomplete="off">
            </div>
          </div>
          <div class="actions">
            <button id="btnGetTransaction">Ambil Data</button>
          </div>
        </div>
        <pre id="gt_result">// Hasil getTransactionQris muncul di sini</pre>
      </section>

      <section class="card span-6">
        <div class="card-header">
          <h3 class="card-title">4) Withdrawal QRIS</h3>
        </div>
        <div class="card-body">
          <div class="row">
            <div>
              <label>Username</label>
              <input id="w_username" placeholder="username" autocomplete="username">
            </div>
            <div>
              <label>Auth Token</label>
              <input id="w_token" placeholder="paste auth token" autocomplete="off">
            </div>
          </div>
          <div class="row">
            <div>
              <label>Nominal (IDR)</label>
              <input id="w_amount" type="number" min="0" step="1" placeholder="cth: 50000">
            </div>
            <div></div>
          </div>
          <div class="actions">
            <button id="btnWithdraw">Tarik Dana</button>
          </div>
        </div>
        <pre id="w_result">// Hasil withdrawalQris muncul di sini</pre>
      </section>

    </div>

    <p class="footer">
      Catatan: Token akan disimpan di <span class="kbd">localStorage</span> di browser Anda agar kolom otomatis terisi. Jangan gunakan di perangkat publik.
    </p>
  </main>

  <script>
    // Helpers
    const $ = (id) => document.getElementById(id);
    const pretty = (obj) => typeof obj === 'string' ? obj : JSON.stringify(obj, null, 2);
    const state = {
      set(u, t){
        if(u) localStorage.setItem('ok.username', u);
        if(t) localStorage.setItem('ok.token', t);
      },
      get(){
        return {
          username: localStorage.getItem('ok.username') || '',
          token: localStorage.getItem('ok.token') || ''
        }
      },
      clear(){
        localStorage.removeItem('ok.username');
        localStorage.removeItem('ok.token');
      }
    };

    // Autofill from saved state
    (function init() {
      const { username, token } = state.get();
      ['lr_username','ga_username','gt_username','w_username'].forEach(id => $(id).value = username);
      ['gt_token','w_token'].forEach(id => $(id).value = token);

      $('clearState').addEventListener('click', () => {
        state.clear();
        alert('Data lokal dihapus.');
        location.reload();
      });
    })();

    async function call(action, data, outElem, afterSuccess){
      const fd = new FormData();
      fd.append('action', action);
      Object.entries(data).forEach(([k,v]) => fd.append(k, v));

      outElem.textContent = 'Memproses...';
      try{
        const res = await fetch('api', { method: 'POST', body: fd });
        const text = await res.text();
        let payload;
        try { payload = JSON.parse(text); } catch { payload = {raw:text}; }
        outElem.textContent = pretty(payload);

        // naive extraction for username/token if present
        if (afterSuccess) afterSuccess(payload);
      }catch(err){
        outElem.textContent = pretty({error:true, message: err.message});
      }
    }

    // 1) Login Request
    $('btnLoginRequest').addEventListener('click', () => {
      const username = $('lr_username').value.trim();
      const password = $('lr_password').value;
      if(!username || !password) return alert('Lengkapi username & password.');
      state.set(username);
      // autofill other username fields
      ['ga_username','gt_username','w_username'].forEach(id => $(id).value = username);
      call('loginRequest', {username, password}, $('lr_result'));
    });

    // 2) Get Auth Token
    $('btnGetAuthToken').addEventListener('click', () => {
      const username = $('ga_username').value.trim();
      const otp = $('ga_otp').value.trim();
      if(!username || !otp) return alert('Lengkapi username & OTP.');
      call('getAuthToken', {username, otp}, $('ga_result'), (payload) => {
        // Try store token if a field named 'auth_token' exists in JSON
        const token = (payload && (payload.auth_token || (payload.data && payload.data.auth_token))) || '';
        if(token){
          state.set(username, token);
          ['gt_token','w_token'].forEach(id => $(id).value = token);
        }
      });
    });

    // 3) Get Transaction QRIS
    $('btnGetTransaction').addEventListener('click', () => {
      const username = $('gt_username').value.trim();
      const authToken = $('gt_token').value.trim();
      if(!username || !authToken) return alert('Lengkapi username & auth token.');
      state.set(username, authToken);
      call('getTransactionQris', {username, authToken}, $('gt_result'));
    });

    // 4) Withdrawal QRIS
    $('btnWithdraw').addEventListener('click', () => {
      const username = $('w_username').value.trim();
      const authToken = $('w_token').value.trim();
      const amount = $('w_amount').value.trim();
      if(!username || !authToken || !amount) return alert('Lengkapi semua kolom.');
      state.set(username, authToken);
      call('withdrawalQris', {username, authToken, amount}, $('w_result'));
    });
  </script>
</body>
</html>
