<%- include('partials/header', { title: 'Permintaan Withdraw' }) %>

<style>
  .custom-scroll::-webkit-scrollbar { width: 2px; height: 2px; }
  .custom-scroll::-webkit-scrollbar-track { background: #f1f1f1; }
  .custom-scroll::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 4px; }
  .custom-scroll:hover::-webkit-scrollbar-thumb { background-color: #94a3b8; }
</style>

<div class="max-w-3xl mt-1 mx-auto px-6 pb-10">

  <!-- Search -->
  <div class="bg-[#f9f9f9] border border-[#dddddd] rounded-[2px] p-4 mb-6">
    <div class="max-w-xs mx-auto">
      <input id="globalSearchInput" type="text" placeholder="Cari username atau email..." 
             class="w-full bg-white border border-[#dddddd] rounded-[2px] px-3 py-2.5 text-[12.5px] font-medium text-gray-800 outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 placeholder:text-[12.5px] placeholder:font-medium placeholder:text-gray-400"
             value="<%= typeof search !== 'undefined' ? search : '' %>" autocomplete="off">
    </div>
  </div>

  <!-- Permintaan Withdraw (Pending) -->
  <div>

    <% const pendingList = withdrawals.filter(w => w.status === 'pending'); %>
    <% if (pendingList.length === 0) { %>
      <div class="bg-white border border-[#dddddd] rounded-[2px] p-8 text-center">
        <p class="text-sm font-medium text-gray-600">Tidak ada permintaan withdraw</p>
      </div>
    <% } else { %>
      <div class="bg-white border border-[#dddddd] rounded-[2px] overflow-hidden">
        <div class="overflow-x-auto custom-scroll" style="max-height: 500px;">
          <table class="w-full text-[12.5px] text-left whitespace-nowrap font-medium">
            <thead class="bg-[#f9f9f9] text-[12.5px] text-gray-800 font-medium border-b border-[#dddddd] sticky top-0 z-10">
              <tr>
                <th class="px-3 py-2.5 font-semibold">Pengguna</th>
                <th class="px-3 py-2.5 font-semibold">Jumlah</th>
                <th class="px-3 py-2.5 font-semibold">Metode</th>
                <th class="px-3 py-2.5 font-semibold">No Rekening</th>
                <th class="px-3 py-2.5 font-semibold">Tanggal</th>
                <th class="px-3 py-2.5 font-semibold text-center">Aksi</th>
              </tr>
            </thead>
            <tbody id="pendingTableBody" class="divide-y divide-[#dddddd] font-medium">
              <% pendingList.forEach(w => { %>
              <tr class="hover:bg-gray-50 cursor-pointer transition-colors"
                  data-id="<%= w._id %>"
                  data-type="withdraw"
                  data-amount="<%= w.amount %>"
                  data-fee="<%= w.fee || 0 %>"
                  data-status="<%= w.status %>"
                  data-created="<%= w.createdAt.toISOString() %>"
                  data-expired=""
                  data-username="<%= w.userId?.username || 'Pengguna Dihapus' %>"
                  data-email="<%= w.userId?.email || '-' %>"
                  data-method="<%= w.method %>"
                  data-account="<%= w.accountNumber || '' %>"
                  data-name="<%= w.accountName || '' %>"
                  data-note="<%= (w.adminNote || '') %>"
                  data-completed="<%= w.completedAt ? w.completedAt.toISOString() : '' %>"
                  onclick="window.location.hash = 'withdraw-' + this.dataset.id">
                <td class="px-3 py-3">
                  <div class="text-[12.5px] font-medium text-gray-800"><%= w.userId ? w.userId.username : 'Pengguna Dihapus' %></div>
                </td>
                <td class="px-3 py-3 text-gray-800">Rp <%= w.amount.toLocaleString('id-ID') %></td>
                <td class="px-3 py-3 text-gray-700"><%= w.method %></td>
                <td class="px-3 py-3">
                  <div class="text-[12.5px] font-medium text-gray-800"><%= w.accountNumber || '-' %></div>
                </td>
                <td class="px-3 py-3 text-gray-800 date-cell" data-timestamp="<%= w.createdAt.toISOString() %>"></td>
                <td class="px-3 py-3" onclick="event.stopPropagation()">
                  <div class="flex items-center justify-center gap-2">
                    <form method="POST" action="/admin/withdraw/success/<%= w._id %>">
                      <button class="bg-blue-500 hover:bg-blue-600 text-white px-3 py-2 rounded-[2px] text-[12.5px] font-medium transition-colors inline-flex items-center gap-1.5">
                        <i class="fas fa-check text-[12.5px]"></i> Setujui
                      </button>
                    </form>
                    <button type="button" onclick="openRejectModal('<%= w._id %>')" class="bg-red-50 hover:bg-red-100 text-red-600 border border-red-200 px-3 py-2 rounded-[2px] text-[12.5px] font-medium transition-colors inline-flex items-center gap-1.5">
                      <i class="fas fa-times text-[12.5px]"></i> Tolak
                    </button>
                  </div>
                </td>
              </tr>
              <% }) %>
            </tbody>
          </table>
        </div>
      </div>
    <% } %>
  </div>
</div>

<!-- ===================== MODAL DETAIL WITHDRAW ===================== -->
<div id="withdrawDetailModal" class="fixed inset-0 z-[150] hidden flex items-center justify-center p-4">
  <div class="absolute inset-0 bg-black/40 backdrop-blur-sm transition-opacity" onclick="closeWithdrawDetailModal()"></div>
  <div class="relative bg-white border border-[#dddddd] rounded-[2px] shadow-sm w-full max-w-md transform transition-all scale-95 opacity-0 duration-200 flex flex-col max-h-[90vh]" id="withdrawDetailContent">
    <div class="px-5 py-3 border-b border-[#dddddd] flex items-center justify-between shrink-0">
      <h2 class="text-sm font-medium text-gray-800">Detail Penarikan</h2>
      <button onclick="closeWithdrawDetailModal()" class="w-7 h-7 flex items-center justify-center rounded-[2px] text-gray-500 hover:text-gray-700 transition-colors"><i class="fas fa-times text-[12.5px]"></i></button>
    </div>
    <div class="p-5 overflow-y-auto custom-scroll">
      <table class="w-full text-[12.5px] border-collapse border border-[#dddddd] mb-4">
        <tbody>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600 w-32">Tipe</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawType">-</td></tr>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600 w-32">ID Penarikan</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800 break-all" id="modalDetailWithdrawId">-</td></tr>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">Pengguna</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawUsername">-</td></tr>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">Email</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawEmail">-</td></tr>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">Status</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawStatus">-</td></tr>
          <tr id="modalDetailWithdrawAdminNoteRow" class="hidden"><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">Keterangan</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawAdminNote"></td></tr>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">Tanggal</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawTanggal">-</td></tr>
          <tr id="modalDetailWithdrawCompletedRow" class="hidden"><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">Tanggal Selesai</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawCompleted">-</td></tr>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">Nominal</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawNominal">Rp 0</td></tr>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">Biaya Admin</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawFee">Rp 0</td></tr>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">Total Terpotong</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawTotalPotong">Rp 0</td></tr>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">Total Diterima</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawDiterima">Rp 0</td></tr>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">Metode</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawMethod">-</td></tr>
          <tr><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-600">No. Rekening</td><td class="px-3 py-2 border border-[#dddddd] font-medium text-gray-800" id="modalDetailWithdrawAccount">-</td></tr>
          <!-- Baris Atas Nama dihapus -->
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- ===================== MODAL REJECT ===================== -->
<div id="rejectModal" class="fixed inset-0 z-[160] hidden flex items-center justify-center p-4">
  <div class="absolute inset-0 bg-black/40 backdrop-blur-sm transition-opacity" onclick="closeRejectModal()"></div>
  <div class="relative bg-white border border-[#dddddd] rounded-[2px] shadow-sm w-full max-w-sm transform transition-all scale-95 opacity-0 duration-200" id="rejectModalContent">
    <div class="px-5 py-3 border-b border-[#dddddd] flex items-center justify-between">
      <h2 class="text-sm font-medium text-gray-800">Konfirmasi Penolakan</h2>
      <button onclick="closeRejectModal()" class="w-7 h-7 flex items-center justify-center rounded-[2px] text-gray-500 hover:text-gray-700 transition-colors">
        <i class="fas fa-times text-[12.5px]"></i>
      </button>
    </div>
    <div class="p-5">
      <p class="text-[12.5px] font-medium text-gray-600 mb-4">
        Silakan isi alasan penolakan di bawah ini
      </p>
      <form id="rejectForm" method="POST" action="" class="flex flex-col gap-3">
        <textarea name="note" placeholder="Tulis alasan penolakan..." rows="3" class="bg-white border border-[#dddddd] rounded-[2px] px-3 py-2 text-[12.5px] font-medium text-gray-800 outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 resize-none placeholder:text-[12.5px] placeholder:font-medium placeholder:text-gray-400" required></textarea>
        <div class="flex gap-3 mt-2">
          <button type="button" onclick="closeRejectModal()" class="flex-1 px-4 py-3 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-[2px] text-[12.5px] transition-colors border border-[#dddddd]">Batal</button>
          <button type="submit" class="flex-1 px-4 py-3 bg-red-500 hover:bg-red-600 text-white font-medium rounded-[2px] text-[12.5px] transition-colors inline-flex items-center justify-center gap-1.5">
            <i class="fas fa-paper-plane text-[12.5px]"></i> Kirim
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
  // ===================== FORMAT TANGGAL DI SISI KLIEN =====================
  function formatDateCell(cell) {
    const timestamp = cell.dataset.timestamp;
    if (!timestamp) return;
    const d = new Date(timestamp);
    const days = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
    const dayName = days[d.getDay()];
    const dateNum = String(d.getDate()).padStart(2, '0');
    const timeStr = d.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }).replace('.', ':');
    cell.textContent = `${dayName} ${dateNum}, ${timeStr}`;
  }

  // ========== FUNGSI FILTER GLOBAL ==========
  (() => {
    const input = document.getElementById('globalSearchInput');
    if (!input) return;

    input.addEventListener('input', function() {
      const query = this.value.toLowerCase().trim();
      const rows = document.querySelectorAll('#pendingTableBody tr');
      rows.forEach(row => {
        const username = row.dataset.username || '';
        const email = row.dataset.email || '';
        row.style.display = (!query || username.includes(query) || email.includes(query)) ? '' : 'none';
      });
    });

    // Jika ada nilai search dari backend, trigger filter
    if (input.value) {
      input.dispatchEvent(new Event('input'));
    }
  })();

  // ========== MODAL REJECT ==========
  function openRejectModal(id) {
    event.stopPropagation();
    const modal = document.getElementById('rejectModal');
    const modalContent = document.getElementById('rejectModalContent');
    document.getElementById('rejectForm').action = '/admin/withdraw/reject/' + id;
    modal.classList.remove('hidden');
    setTimeout(() => {
      modalContent.classList.remove('scale-95', 'opacity-0');
      modalContent.classList.add('scale-100', 'opacity-100');
    }, 10);
  }

  function closeRejectModal() {
    const modal = document.getElementById('rejectModal');
    const modalContent = document.getElementById('rejectModalContent');
    modalContent.classList.remove('scale-100', 'opacity-100');
    modalContent.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
      modal.classList.add('hidden');
      document.getElementById('rejectForm').reset();
    }, 200);
  }

  document.getElementById('rejectModal').addEventListener('click', function(e) {
    if (e.target === this) closeRejectModal();
  });

  // ========== MODAL DETAIL WITHDRAW ==========
  function getWithdrawDataFromRow(row) {
    return {
      id: row.dataset.id,
      type: row.dataset.type,
      amount: row.dataset.amount,
      fee: row.dataset.fee,
      status: row.dataset.status,
      created: row.dataset.created,
      expired: row.dataset.expired || null,
      username: row.dataset.username,
      email: row.dataset.email,
      method: row.dataset.method,
      account: row.dataset.account,
      name: row.dataset.name,   // tetap ambil, tapi tidak ditampilkan
      note: row.dataset.note,
      completed: row.dataset.completed || null
    };
  }

  function openWithdrawDetailModal(transactionData) {
    document.getElementById('modalDetailWithdrawType').innerHTML = '<span class="inline-flex items-center gap-1 text-[12.5px] font-medium text-red-600 bg-red-50 px-2 py-0.5 rounded-[2px]"><i class="fas fa-arrow-up text-[10px]"></i> Withdraw</span>';
    document.getElementById('modalDetailWithdrawId').innerText = transactionData.id;
    document.getElementById('modalDetailWithdrawUsername').innerText = transactionData.username || '-';
    document.getElementById('modalDetailWithdrawEmail').innerText = transactionData.email || '-';

    const formatOpts = { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false };
    const created = new Date(transactionData.created);
    document.getElementById('modalDetailWithdrawTanggal').innerText = created.toLocaleString('id-ID', formatOpts).replace(/\./g, ':');

    if (transactionData.completed) {
      const compDate = new Date(transactionData.completed);
      document.getElementById('modalDetailWithdrawCompleted').innerText = compDate.toLocaleString('id-ID', formatOpts).replace(/\./g, ':');
      document.getElementById('modalDetailWithdrawCompletedRow').classList.remove('hidden');
    } else document.getElementById('modalDetailWithdrawCompletedRow').classList.add('hidden');

    const adminNoteRow = document.getElementById('modalDetailWithdrawAdminNoteRow');
    const adminNoteEl = document.getElementById('modalDetailWithdrawAdminNote');
    if (
      (transactionData.status === 'expired' || transactionData.status === 'rejected') &&
      transactionData.note &&
      transactionData.note.trim() !== ''
    ) {
      adminNoteEl.innerText = transactionData.note;
      adminNoteRow.classList.remove('hidden');
    } else {
      adminNoteRow.classList.add('hidden');
    }

    const nominal = Math.abs(parseInt(transactionData.amount)) || 0;
    const fee = parseInt(transactionData.fee) || 0;
    const totalPotong = nominal + fee;
    document.getElementById('modalDetailWithdrawNominal').innerText = `Rp ${nominal.toLocaleString('id-ID')}`;
    document.getElementById('modalDetailWithdrawFee').innerText = `Rp ${fee.toLocaleString('id-ID')}`;
    document.getElementById('modalDetailWithdrawTotalPotong').innerText = `Rp ${totalPotong.toLocaleString('id-ID')}`;
    document.getElementById('modalDetailWithdrawDiterima').innerText = `Rp ${nominal.toLocaleString('id-ID')}`;

    let statusHTML = '';
    const st = transactionData.status;
    if (st === 'paid' || st === 'success') statusHTML = '<span class="text-[12.5px] font-medium text-blue-500">Completed</span>';
    else if (st === 'pending') statusHTML = '<span class="text-[12.5px] font-medium text-[#eab308]">Pending</span>';
    else statusHTML = '<span class="text-[12.5px] font-medium text-[#dc2626]">Failed</span>';
    document.getElementById('modalDetailWithdrawStatus').innerHTML = statusHTML;

    document.getElementById('modalDetailWithdrawMethod').innerText = transactionData.method || '-';
    document.getElementById('modalDetailWithdrawAccount').innerText = transactionData.account || '-';
    // Tidak lagi mengisi Atas Nama

    const modal = document.getElementById('withdrawDetailModal');
    const modalContent = document.getElementById('withdrawDetailContent');
    modal.classList.remove('hidden');
    setTimeout(() => { modalContent.classList.remove('scale-95', 'opacity-0'); modalContent.classList.add('scale-100', 'opacity-100'); }, 10);
    document.body.style.overflow = 'hidden';
  }

  function closeWithdrawDetailModal() {
    if (window.location.hash.startsWith('#withdraw-')) {
      history.back();
      setTimeout(() => {
        if (window.location.hash.startsWith('#withdraw-')) window.location.hash = '';
      }, 100);
    } else {
      const modal = document.getElementById('withdrawDetailModal');
      const modalContent = document.getElementById('withdrawDetailContent');
      modalContent.classList.remove('scale-100', 'opacity-100');
      modalContent.classList.add('scale-95', 'opacity-0');
      setTimeout(() => { modal.classList.add('hidden'); document.body.style.overflow = ''; }, 200);
    }
  }

  // ========== HASH ROUTER ==========
  function handleWithdrawRouter() {
    const hash = window.location.hash;
    if (!hash.startsWith('#withdraw-')) return;
    const withdrawId = hash.replace('#withdraw-', '');
    const row = document.querySelector(`tr[data-id="${withdrawId}"]`);
    if (!row) {
      closeWithdrawDetailModal();
      history.replaceState(null, null, window.location.pathname + window.location.search);
      return;
    }
    const data = getWithdrawDataFromRow(row);
    openWithdrawDetailModal(data);
  }

  window.addEventListener('hashchange', handleWithdrawRouter);
  window.addEventListener('popstate', function() {
    if (!window.location.hash.startsWith('#withdraw-')) {
      closeWithdrawDetailModal();
    }
  });

  document.addEventListener('DOMContentLoaded', function() {
    // Format semua sel tanggal di tabel
    document.querySelectorAll('.date-cell').forEach(formatDateCell);

    if (window.location.hash.startsWith('#withdraw-')) {
      handleWithdrawRouter();
    }
  });
</script>

<%- include('partials/footer') %>