<x-admin-layout>
@section('title', $page . ' | ' . get_setting('site_name'))
  <div class="mt-4 grid grid-cols-12 gap-4 sm:mt-5 sm:gap-5 lg:mt-6 lg:gap-6">
    <div class="col-span-12">
      <div x-data="{activeTab:'WD'}" class="tabs flex flex-col">
        <div
          class="is-scrollbar-hidden overflow-x-auto rounded-lg bg-slate-200 text-slate-600 dark:bg-navy-800 dark:text-navy-200"
        >
          <div class="tabs-list flex px-1.5 py-1">
              <div
                x-data="usePopper({placement:'bottom-start',offset:4})"
                @click.outside="isShowPopper && (isShowPopper = false)"
                class="inline-flex ml-4"
              >
                <button
                  class="btn space-x-2 bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90"
                  x-ref="popperRef"
                  @click="isShowPopper = !isShowPopper"
                ><i class="fas fa-window-maximize"></i>
                  <span>Status</span>
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    class="size-4 transition-transform duration-200"
                    :class="isShowPopper && 'rotate-180'"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    stroke-width="2"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      d="M19 9l-7 7-7-7"
                    />
                  </svg>
                </button>
                <div x-ref="popperRoot" class="popper-root" :class="isShowPopper && 'show'">
                  <div
                    class="popper-box rounded-md border border-slate-150 bg-white py-1.5 font-inter dark:border-navy-500 dark:bg-navy-700"
                  >
                    <ul>
                      <li>
                        <a
                          @click="activeTab = 'WD'"
                          id="pending"
                          href="javascript:void(0);"
                          class="flex h-8 items-center px-3 pr-8 font-medium tracking-wide outline-none transition-all hover:bg-primary hover:text-white focus:bg-primary focus:text-white dark:hover:bg-accent dark:focus:bg-accent"
                          >Pending</a
                        >
                      </li>
                      <li>
                        <a
                          @click="activeTab = 'WD'"
                          id="approved"
                          href="javascript:void(0);"
                          class="flex h-8 items-center px-3 pr-8 font-medium tracking-wide outline-none transition-all hover:bg-primary hover:text-white focus:bg-primary focus:text-white dark:hover:bg-accent dark:focus:bg-accent"
                          >Approved</a
                        >
                      </li>
                      <li>
                        <a
                          @click="activeTab = 'WD'"
                          id="rejected"
                          href="javascript:void(0);"
                          class="flex h-8 items-center px-3 pr-8 font-medium tracking-wide outline-none transition-all hover:bg-primary hover:text-white focus:bg-primary focus:text-white dark:hover:bg-accent dark:focus:bg-accent"
                          >Rejected</a
                        >
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
          </div>
        </div>
        <div class="tab-content pt-4">
          <div
            x-show="activeTab === 'WD'"
            x-transition:enter="transition-all duration-500 easy-in-out"
            x-transition:enter-start="opacity-0 [transform:translate3d(1rem,0,0)]"
            x-transition:enter-end="opacity-100 [transform:translate3d(0,0,0)]"
          >
            <div class="overflow-x-auto">
              <table class="is-hoverable w-full text-left">
                <thead>
                  <tr>
                    <th class="whitespace-nowrap rounded-tl-lg bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5">
                         Username </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> Method </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> Address </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> Status </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> Crypto </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> Amount </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5"> Fee </th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5">Date</th>
                    <th class="whitespace-nowrap bg-slate-200 px-4 py-3 font-semibold uppercase text-slate-800 dark:bg-navy-800 dark:text-navy-100 lg:px-5">Action</th>
                  </tr>
                </thead>
                <tbody id="withdrawals">
                  <tr>
                    <td colspan="9" class="text-center py-4"><div class="w-full px-6 py-4"><div class="skeleton animate-wave h-3 w-full rounded bg-slate-150 dark:bg-navy-500"></div><div class="skeleton animate-wave mt-4 h-3 w-8/12 rounded bg-slate-150 dark:bg-navy-500"></div></div></td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- Pagination -->
            <div id="pagination" class="mt-4 flex justify-center"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
@push('scripts')
<script>
$(document).ready(function() {
    let curStatus = 0;
    function loadWd(page = 1, status = 0) {
      curStatus = status;
      $.ajax({
        url: "/admin/withdrawals/load/"+status,
        type: "GET",
        data: { page: page },
        dataType: "json",
        beforeSend: function () {
            $("#withdrawals").html('<tr><td colspan="9" class="text-center py-4"><div class="w-full px-6 py-4"><div class="skeleton animate-wave h-3 w-full rounded bg-slate-150 dark:bg-navy-500"></div><div class="skeleton animate-wave mt-4 h-3 w-8/12 rounded bg-slate-150 dark:bg-navy-500"></div></div></td></tr>');
        },
        success: function (data) {
            var html = "";
            if (data.records.length > 0) {
                data.records.forEach(function (item) {
                  html += `
                    <tr id="wdid${item.id}" class="border-y border-transparent border-b-slate-200 dark:border-b-navy-500">
                    <td class="whitespace-nowrap px-4 py-3 sm:px-5"><a href="/admin/user/${item.user_id}" target="_blank" class="text-primary">${item.username}</a></td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">
                          ${item.method}
                      </td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.address}</td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">
                          <span class="badge bg-${item.status.color} text-white">
                            ${item.status.text}
                          </span>
                      </td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.crypto}</td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.amount}</td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.fee}</td>
                      <td class="whitespace-nowrap px-4 py-3 sm:px-5">${item.date}</td>
                      <td class="flex items-center">
                        ${item.status.text == 'Pending' ? `
                            <button class="btn-approve mt-1 edit-btn btn min-w-[7rem] rounded-full bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90" data-id="${item.id}">Approve</button>
                        ` : ''}
                        ${item.status.text == 'Pending' ? `
                            <button class="btn-reject mt-1 btn min-w-[7rem] rounded-full border border-slate-300 font-medium text-slate-800 hover:bg-slate-150 focus:bg-slate-150 active:bg-slate-150/80 dark:border-navy-450 dark:text-navy-50 dark:hover:bg-navy-500 dark:focus:bg-navy-500 dark:active:bg-navy-500/90" data-id="${item.id}">Reject</button>
                        ` : ''}
                      </td>
                    </tr>`;
                });
          } else {
            html = '<tr><td colspan="9" class="text-center py-4">No data available</td></tr>';
          }
          $("#withdrawals").html(html);

        var paginationHtml = `
            <ol class="pagination">
                <li class="rounded-l-full bg-slate-150 dark:bg-navy-500">
                    <a href="#" class="pagination-btn flex size-8 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:text-navy-200 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="${data.prev_page}" ${data.prev_page ? "" : "disabled"}>
                        <svg xmlns="http://www.w3.org/2000/svg" class="size-4" fill="none" viewbox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
                        </svg>
                    </a>
                </li>`;
        
        var startPage = Math.max(1, data.current_page - 2);
        var endPage = Math.min(data.total_pages, startPage + 4);
        
        if (startPage > 1) {
            paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">
                <a href="#" class="pagination-btn flex h-8 min-w-[2rem] items-center justify-center rounded-full px-3 leading-tight transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="1">1</a>
            </li>`;
            if (startPage > 2) {
                paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">...</li>`;
            }
        }
        
        for (var i = startPage; i <= endPage; i++) {
            paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">
                <a href="#" class="pagination-btn flex h-8 min-w-[2rem] items-center justify-center rounded-full px-3 ${i === data.current_page ? 'bg-primary px-3 leading-tight text-white transition-colors hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90' : 'leading-tight transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90'}" data-page="${i}">${i}</a>
            </li>`;
        }
        
        if (endPage < data.total_pages) {
            if (endPage < data.total_pages - 1) {
                paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">...</li>`;
            }
            paginationHtml += `<li class="bg-slate-150 dark:bg-navy-500">
                <a href="#" class="pagination-btn flex h-8 min-w-[2rem] items-center justify-center rounded-full px-3 leading-tight transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="${data.total_pages}">${data.total_pages}</a>
            </li>`;
        }
        
        paginationHtml += `
            <li class="rounded-r-full bg-slate-150 dark:bg-navy-500">
                <a href="#" class="pagination-btn flex size-8 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-300 focus:bg-slate-300 active:bg-slate-300/80 dark:text-navy-200 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90" data-page="${data.next_page}" ${data.next_page ? "" : "disabled"}>
                    <svg xmlns="http://www.w3.org/2000/svg" class="size-4" fill="none" viewbox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                    </svg>
                </a>
            </li>
        </ol>`;
        
        $("#pagination").html(paginationHtml);

        },
      });
    }

    $("#pending").click(function() {
        loadWd(1, 0);
    });

    $("#approved").click(function() {
        loadWd(1, 1);
    });
    
    $("#rejected").click(function() {
        loadWd(1, 2);
    });
    loadWd(1, 1);
    $(document).on("click", ".pagination-btn", function (e) {
      e.preventDefault();
      var page = $(this).data("page");
      if (page) loadWd(page, curStatus);
    });
    
    $(document).on("click", ".btn-approve", function () {
        let id = $(this).data("id");
        updateStatus(id, 1);
    });
    
    $(document).on("click", ".btn-reject", function () {
        let id = $(this).data("id");
        updateStatus(id, 2);
    });
    
    function updateStatus(id, status) {
        let theme = localStorage.getItem("_x_darkMode_on") === "true" ? "dark" : "light";
        $.ajax({
            url: "/admin/withdrawals/update-status",
            type: "POST",
            data: {
                _token: $('meta[name="csrf-token"]').attr("content"), 
                id: id,
                status: status
            },
                success: function(response) {
                    if (response.success) {
                        $("#wdid" + id).remove();
                        let swalOptions = {
                            icon: "success",
                            title: "Success!",
                            html: `<p>${response.message}</p>`,
                            toast: true,
                            position: "bottom-end",
                            showConfirmButton: false,
                            customClass: {
                                popup: "toast-popup",
                                title: "toast-title",
                                content: "toast-content"
                            },
                            showCloseButton: true,
                            closeButtonHtml: "<i class='fas fa-times'></i>"
                        };
                        
                        if (theme === "dark") {
                            swalOptions.background = "#1E293B";
                            swalOptions.color = "#F8FAFC";
                            swalOptions.confirmButtonColor = "#4F46E5";
                        }

                        Swal.fire(swalOptions);

                        if ($("#withdrawals tr").length === 0) {
                            loadWd(1, 0);
                        }
                    } else {
                        let swalOptions = {
                            icon: "error",
                            title: "Failed!",
                            html: `<p>${response.error}</p>`,
                            toast: true,
                            position: "bottom-end",
                            showConfirmButton: false,
                            customClass: {
                                popup: "toast-popup",
                                title: "toast-title",
                                content: "toast-content"
                            },
                            showCloseButton: true,
                            closeButtonHtml: "<i class='fas fa-times'></i>"
                        };
                        
                        if (theme === "dark") {
                            swalOptions.background = "#1E293B";
                            swalOptions.color = "#F8FAFC";
                            swalOptions.confirmButtonColor = "#4F46E5";
                        }
                        
                        Swal.fire(swalOptions);
                    }
                },
            error: function () {
                alert("Error updating status!");
            }
        });
    }

});
</script>

@endpush
</x-admin-layout>
