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

<style>
  :root {
    --blue-500: #3b82f6;
    --blue-50: #eff6ff;
  }
  .text-blue-500 { color: var(--blue-500); }
  .bg-blue-50 { background-color: var(--blue-50); }
  
  .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 mx-auto px-6 pb-2">

  <% if (typeof success !== 'undefined' && success) { %>
    <div class="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-[2px] mb-4 text-[12.5px] font-medium flex items-center gap-3">
      <div class="w-7 h-7 rounded-[2px] bg-green-100 flex items-center justify-center shrink-0">
        <i class="fas fa-check-circle text-[12.5px]"></i>
      </div>
      <p><%= success %></p>
    </div>
  <% } %>

  <% if (typeof error !== 'undefined' && error) { %>
    <div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-[2px] mb-4 text-[12.5px] font-medium flex items-center gap-3">
      <div class="w-7 h-7 rounded-[2px] bg-red-100 flex items-center justify-center shrink-0">
        <i class="fas fa-exclamation-circle text-[12.5px]"></i>
      </div>
      <p><%= error %></p>
    </div>
  <% } %>

  <!-- Judul -->
  <div class="flex items-center gap-2 mb-3">
    <h2 class="text-base font-medium text-gray-800">Profil User</h2>
  </div>

  <% 
    let rawApiKey = '';
    if (typeof apiKeys !== 'undefined' && apiKeys.length > 0) {
      rawApiKey = apiKeys[0].key;
    } else if (user.apiKey) {
      rawApiKey = user.apiKey;
    }
    let maskedApiKey = rawApiKey ? '••••••••' : 'Belum ada API Key';
  %>

  <!-- Tabel informasi pengguna -->
  <div class="w-full overflow-hidden mb-4">
    <table class="w-full text-[12.5px] border-collapse border border-gray-300 table-fixed">
      <tbody>
        <tr>
          <td class="px-3 py-3 border border-gray-300 font-medium text-gray-800 w-1/3">ID User</td>
          <td class="px-3 py-3 border border-gray-300 text-gray-800 font-medium truncate"><%= (user._id.toString()).slice(10) %></td>
        </tr>    
        <tr>
          <td class="px-3 py-3 border border-gray-300 font-medium text-gray-800">Username</td>
          <td class="px-3 py-3 border border-gray-300 text-gray-800 font-medium truncate"><%= user.username %></td>
        </tr>
        <tr>
          <td class="px-3 py-3 border border-gray-300 font-medium text-gray-800">Email</td>
          <td class="px-3 py-3 border border-gray-300 text-gray-800 font-medium truncate"><%= user.email %></td>
        </tr>
        <tr>
          <td class="px-3 py-3 border border-gray-300 font-medium text-gray-800">Role</td>
          <td class="px-3 py-3 border border-gray-300 text-gray-800 font-medium truncate capitalize"><%= user.role %></td>
        </tr>
        <tr>
          <td class="px-3 py-3 border border-gray-300 font-medium text-gray-800">Tanggal Bergabung</td>
          <td class="px-3 py-3 border border-gray-300 text-gray-800 font-medium truncate">
            <%= new Date(user.createdAt).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' }) %>
          </td>
        </tr>
        <!-- Nama Project -->
        <tr>
          <td class="px-3 py-3 border border-gray-300 font-medium text-gray-800">Nama Project</td>
          <td class="px-3 py-3 border border-gray-300 text-gray-800 font-medium truncate">
            <%= user.projectName || '-' %>
          </td>
        </tr>
        <!-- Callback URL -->
        <tr>
          <td class="px-3 py-3 border border-gray-300 font-medium text-gray-800">Callback URL</td>
          <td class="px-3 py-3 border border-gray-300 text-gray-800 font-medium truncate">
            <% if (user.callbackUrl && user.callbackUrl.trim() !== '') { %>
              <span title="<%= user.callbackUrl %>"><%= user.callbackUrl %></span>
            <% } else { %>
              <span class="text-gray-500">-</span>
            <% } %>
          </td>
        </tr>
        <!-- Logo URL (merchantLogoUrl) -->
        <tr>
          <td class="px-3 py-3 border border-gray-300 font-medium text-gray-800">Logo Merchant</td>
          <td class="px-3 py-3 border border-gray-300 text-gray-800 font-medium truncate">
            <% if (user.merchantLogoUrl && user.merchantLogoUrl.trim() !== '') { %>
              <span title="<%= user.merchantLogoUrl %>"><%= user.merchantLogoUrl %></span>
            <% } else { %>
              <span class="text-gray-500">-</span>
            <% } %>
          </td>
        </tr>
        <tr>
          <td class="px-3 py-3 border border-gray-300 font-medium text-gray-800">API Key</td>
          <td class="px-3 py-3 border border-gray-300 text-gray-800 font-medium">
            <div class="flex items-center gap-1 min-w-0">
              <span id="tableApiKeyDisplay" class="truncate"><%= maskedApiKey %></span>
              <% if (rawApiKey) { %>
                <button type="button" onclick="toggleTableApiKey()" class="ml-1 text-gray-500 hover:text-gray-800 p-1 rounded-[2px] hover:bg-gray-100 shrink-0" title="Tampilkan/Sembunyikan API Key">
                  <i id="tableApiKeyToggleIcon" class="far fa-eye text-[12.5px]"></i>
                </button>
                <button type="button" onclick="copyTableApiKey()" class="ml-1 text-gray-500 hover:text-gray-800 p-1 rounded-[2px] hover:bg-gray-100 shrink-0" title="Salin API Key">
                  <i class="far fa-copy text-[12.5px]"></i>
                </button>
              <% } %>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>

  <!-- Tombol edit -->
  <button onclick="openEditInfoModal()" class="bg-blue-500 hover:bg-blue-600 text-white w-full px-4 py-3 rounded-[2px] text-[12.5px] font-medium shadow-sm transition-all flex items-center justify-center gap-2 mb-6">
    <i class="fas fa-pen-to-square text-[12.5px]"></i> Edit Informasi
  </button>

  <!-- Modal Edit Informasi -->
  <div id="editInfoModal" class="fixed inset-0 z-[150] hidden flex items-center justify-center p-6">
    <div class="absolute inset-0 bg-black/40 backdrop-blur-sm" onclick="closeEditInfoModal()"></div>
    <div class="relative bg-white border border-[#dddddd] rounded-[2px] shadow-sm w-full max-w-sm">
      <div class="px-5 py-3 border-b border-[#dddddd] flex items-center justify-between">
        <h3 class="text-sm font-medium text-gray-800">Edit Informasi</h3>
        <button onclick="closeEditInfoModal()" class="w-7 h-7 flex items-center justify-center rounded-[2px] text-gray-800 hover:bg-gray-100">
          <i class="fas fa-times text-sm"></i>
        </button>
      </div>
      <div class="p-5">
        <form method="POST" action="/profile" id="editProfileForm" class="flex flex-col gap-4">
          <!-- Email -->
          <div>
            <label class="block text-[12.5px] font-medium text-gray-700 mb-2">Alamat Email</label>
            <input name="email" type="email" value="<%= user.email %>" class="w-full bg-white border border-[#dddddd] rounded-[2px] px-3 py-3 text-[12.5px] font-medium text-gray-800 outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500" required>
          </div>

          <!-- Password -->
          <div>
            <label class="block text-[12.5px] font-medium text-gray-700 mb-2">Password Baru <span class="text-xs text-gray-500">(opsional)</span></label>
            <div class="relative">
              <input id="newPassword" name="newPassword" type="password" class="w-full bg-white border border-[#dddddd] rounded-[2px] px-3 py-3 pr-10 text-[12.5px] font-medium text-gray-800 outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500" placeholder="••••••••">
              <button type="button" id="togglePassword" class="absolute right-2 top-1/2 -translate-y-1/2 w-7 h-7 text-gray-500 hover:text-gray-800 flex items-center justify-center">
                <i id="toggleIcon" class="far fa-eye text-[12.5px]"></i>
              </button>
            </div>
          </div>

          <!-- Nama Project -->
          <div>
            <label class="block text-[12.5px] font-medium text-gray-700 mb-2">Nama Project</label>
            <input 
              name="projectName" 
              type="text" 
              id="projectNameInput"
              value="<%= user.projectName || '' %>" 
              placeholder="Nama aplikasi/website Anda" 
              class="w-full bg-white border border-[#dddddd] rounded-[2px] px-3 py-3 text-[12.5px] font-medium text-gray-800 outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
            >
          </div>

          <!-- Callback URL -->
          <div>
            <label class="block text-[12.5px] font-medium text-gray-700 mb-2">Callback URL</label>
            <input 
              name="callbackUrl" 
              type="url" 
              id="callbackUrlInput"
              value="<%= user.callbackUrl || '' %>" 
              placeholder="https://contoh.com/webhook" 
              class="w-full bg-white border border-[#dddddd] rounded-[2px] px-3 py-3 text-[12.5px] font-medium text-gray-800 outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
            >
            <p class="text-[11px] text-gray-500 mt-1">URL akan dipanggil saat status invoice paid.</p>
            <p id="callbackUrlError" class="text-[11px] text-red-500 mt-1 hidden">Format URL tidak valid. Harap gunakan URL lengkap (https://...)</p>
          </div>

          <!-- Logo URL (Merchant) -->
          <div>
            <label class="block text-[12.5px] font-medium text-gray-700 mb-2">
              URL Logo Merchant
              <span class="text-xs text-gray-500">(opsional)</span>
            </label>
            <input 
              name="merchantLogoUrl" 
              type="url" 
              id="merchantLogoUrlInput"
              value="<%= user.merchantLogoUrl || '' %>" 
              placeholder="https://example.com/logo.png" 
              class="w-full bg-white border border-[#dddddd] rounded-[2px] px-3 py-3 text-[12.5px] font-medium text-gray-800 outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
            >
            <p class="text-[11px] text-gray-500 mt-1">URL logo ditampilkan di halaman pembayaran</p>
            <p id="merchantLogoUrlError" class="text-[11px] text-red-500 mt-1 hidden">Format URL tidak valid. Harap gunakan URL lengkap (https://...).</p>
          </div>

          <!-- API Key Field -->
          <div>
            <div class="flex items-center justify-between mb-2">
              <label class="text-[12.5px] font-medium text-gray-700">API Key</label>
              <button type="button" onclick="regenerateApiKeyFromModal(event)" class="text-[12.5px] font-medium text-blue-500 hover:text-blue-600 transition-colors bg-transparent border-0 cursor-pointer">
                Generate Ulang
              </button>
            </div>
            <div class="flex gap-2">
              <div class="relative flex-1">
                <input id="modalApiKeyInput" type="password" readonly value="<%= rawApiKey %>" class="w-full border border-[#dddddd] rounded-[2px] px-3 py-3 pr-10 text-[12.5px] font-medium text-gray-800 outline-none">
                <button type="button" id="toggleModalApiKey" class="absolute right-2 top-1/2 -translate-y-1/2 w-7 h-7 text-gray-500 hover:text-gray-800 flex items-center justify-center">
                  <i id="modalApiKeyToggleIcon" class="far fa-eye text-[12.5px]"></i>
                </button>
              </div>
              <button type="button" onclick="copyApiKeyFromModal()" class="bg-blue-500 hover:bg-blue-600 text-white px-3 py-3 rounded-[2px] text-[12.5px] font-medium transition-colors whitespace-nowrap" title="Salin API Key">
                <i class="far fa-copy text-[12.5px]"></i>
              </button>
            </div>
          </div>

          <!-- Submit -->
          <button type="submit" class="w-full bg-blue-500 hover:bg-blue-600 text-white py-3 rounded-[2px] text-[12.5px] font-medium transition-colors flex items-center justify-center gap-2">
            <i class="fas fa-save text-[12.5px]"></i> Simpan Profil
          </button>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
  // ================== GLOBAL VARIABEL ==================
  window.rawApiKeyValue = '<%= rawApiKey.replace(/'/g, "\\'") %>';
  let isTableApiKeyVisible = false;

  // ================== MODAL EDIT INFORMASI ==================
  function openEditInfoModal() {
    document.getElementById('editInfoModal').classList.remove('hidden');
    document.getElementById('modalApiKeyInput').value = window.rawApiKeyValue;
    document.getElementById('modalApiKeyInput').type = 'password';
    document.getElementById('modalApiKeyToggleIcon').className = 'far fa-eye text-[12.5px]';
  }
  function closeEditInfoModal() {
    document.getElementById('editInfoModal').classList.add('hidden');
  }

  // ================== TOGGLE PASSWORD ==================
  document.addEventListener('DOMContentLoaded', function() {
    const togglePassword = document.getElementById('togglePassword');
    const passwordInput = document.getElementById('newPassword');
    const toggleIcon = document.getElementById('toggleIcon');

    if (togglePassword && passwordInput) {
      togglePassword.addEventListener('click', function (e) {
        e.preventDefault();
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);
        if (type === 'text') {
          toggleIcon.classList.replace('fa-eye', 'fa-eye-slash');
        } else {
          toggleIcon.classList.replace('fa-eye-slash', 'fa-eye');
        }
      });
    }

    // TOGGLE API KEY DI MODAL
    const toggleModalApiKey = document.getElementById('toggleModalApiKey');
    const modalApiKeyInput = document.getElementById('modalApiKeyInput');
    const modalApiKeyToggleIcon = document.getElementById('modalApiKeyToggleIcon');

    if (toggleModalApiKey && modalApiKeyInput) {
      toggleModalApiKey.addEventListener('click', function (e) {
        e.preventDefault();
        const type = modalApiKeyInput.getAttribute('type') === 'password' ? 'text' : 'password';
        modalApiKeyInput.setAttribute('type', type);
        if (type === 'text') {
          modalApiKeyToggleIcon.classList.replace('fa-eye', 'fa-eye-slash');
        } else {
          modalApiKeyToggleIcon.classList.replace('fa-eye-slash', 'fa-eye');
        }
      });
    }

    // ================== VALIDASI CALLBACK URL & LOGO URL ==================
    const editForm = document.getElementById('editProfileForm');
    if (editForm) {
      editForm.addEventListener('submit', function(e) {
        const callbackInput = document.getElementById('callbackUrlInput');
        const callbackErrorEl = document.getElementById('callbackUrlError');
        const merchantLogoInput = document.getElementById('merchantLogoUrlInput');
        const merchantLogoErrorEl = document.getElementById('merchantLogoUrlError');
        
        // Reset error
        callbackErrorEl.classList.add('hidden');
        merchantLogoErrorEl.classList.add('hidden');

        // Validasi callback URL jika diisi
        if (callbackInput && callbackInput.value.trim() !== '') {
          try {
            const url = new URL(callbackInput.value.trim());
            if (!['http:', 'https:'].includes(url.protocol)) {
              throw new Error('Invalid protocol');
            }
          } catch (err) {
            e.preventDefault();
            callbackErrorEl.classList.remove('hidden');
            callbackInput.focus();
            return;
          }
        }

        // Validasi logo URL jika diisi
        if (merchantLogoInput && merchantLogoInput.value.trim() !== '') {
          try {
            new URL(merchantLogoInput.value.trim());
          } catch (err) {
            e.preventDefault();
            merchantLogoErrorEl.classList.remove('hidden');
            merchantLogoInput.focus();
            return;
          }
        }
      });
    }
  });

  // ================== TOGGLE API KEY DI TABEL UTAMA ==================
  function toggleTableApiKey() {
    const displayEl = document.getElementById('tableApiKeyDisplay');
    const toggleIcon = document.getElementById('tableApiKeyToggleIcon');
    if (!displayEl || !toggleIcon) return;
    if (isTableApiKeyVisible) {
      displayEl.innerText = '••••••••';
      toggleIcon.className = 'far fa-eye text-[12.5px]';
    } else {
      displayEl.innerText = window.rawApiKeyValue;
      toggleIcon.className = 'far fa-eye-slash text-[12.5px]';
    }
    isTableApiKeyVisible = !isTableApiKeyVisible;
  }

  // ================== SALIN API KEY DARI TABEL UTAMA ==================
  function copyTableApiKey() {
    if (!window.rawApiKeyValue) {
      alert('Tidak ada API Key untuk disalin.');
      return;
    }
    navigator.clipboard.writeText(window.rawApiKeyValue).then(() => {
      alert('API Key disalin ke clipboard');
    }).catch(() => {
      alert('Gagal menyalin');
    });
  }

  // ================== REGENERATE API KEY ==================
  async function regenerateApiKeyFromModal(event) {
    const btn = event.target;
    if (!confirm('Apakah Anda yakin ingin membuat kunci API baru? Kunci yang lama tidak akan bisa digunakan lagi dan transaksi yang berjalan bisa terhenti.')) {
      return;
    }
    const originalText = btn.innerText;
    btn.disabled = true;
    btn.innerText = '...';
    try {
      const res = await fetch('/api/user/api-key/regenerate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include'
      });
      const data = await res.json();
      if (data.apiKey) {
        window.rawApiKeyValue = data.apiKey;
        document.getElementById('modalApiKeyInput').value = data.apiKey;
        const displayEl = document.getElementById('tableApiKeyDisplay');
        const toggleIcon = document.getElementById('tableApiKeyToggleIcon');
        if (displayEl) displayEl.innerText = '••••••••';
        if (toggleIcon) toggleIcon.className = 'far fa-eye text-[12.5px]';
        isTableApiKeyVisible = false;
        alert('API Key berhasil diperbarui!');
        window.location.reload();
      } else {
        alert(data.error || 'Gagal generate ulang API key');
      }
    } catch (err) {
      alert('Terjadi kesalahan saat generate ulang API key');
    } finally {
      btn.disabled = false;
      btn.innerText = originalText;
    }
  }

  // ================== COPY API KEY DARI MODAL ==================
  function copyApiKeyFromModal() {
    const input = document.getElementById('modalApiKeyInput');
    if (!input.value) return;
    navigator.clipboard.writeText(input.value).then(() => {
      alert('API Key disalin ke clipboard');
    }).catch(() => {
      alert('Gagal menyalin');
    });
  }
</script>

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