<%- include('header.ejs') %>

  <div class="main">
    <div class="container statistical-container" id="statisticalContainer">

    <div class="filter-and-search-container row align-items-start">
        <div class=" col search-bar my-2">
          <input type="text" id="searchInput" placeholder="Tìm theo Tên, SĐT, Code" />
          <button id="searchButton">Tìm</button>
        </div>
    </div>

      <div class="table-responsive">
        <table class="table align-middle table-success table-striped">
          <thead>
            <tr>
                
              <th scope="col">Report ID</th>
              <th scope="col">Mã Code</th>
              <th scope="col">Số điện thoại</th>
              <th scope="col">Số Mệnh Giá</th>
              <th scope="col">Trạng thái</th>
              <th scope="col">Topup</th>
              <th scope="col">Thời Gian</th>
            </tr>
          </thead>
          <tbody id="qrTableBody">
            <% for (const qr in qrCodesFailed) { %>
              <tr>
                  
                <td>
                  <%= qrCodesFailed[qr].topupTransaction.topupReport.id %>
                </td>
                <td>
                  <%= qrCodesFailed[qr].code %>
                </td>
                <td>
                  <%= qrCodesFailed[qr].topupTransaction.phone %>
                </td>
                <td>
                    <%= new Intl.NumberFormat('vi-VN').format(qrCodesFailed[qr].topupTransaction.amount) %> VNĐ
                </td>
                <td>
                  <span class="badge bg-danger"><%= qrCodesFailed[qr].topupTransaction.topupReport.description === 'Unknow' ? 'Worldsms Không Xác Định' : qrCodesFailed[qr].topupTransaction.topupReport.description %></span>
                </td>
                <td class="actions">
                  <button class="edit" data-id="<%= qrCodesFailed[qr].topupTransaction.topupReport.id %>">
                    <i class="fa fa-edit"></i>  Gửi lại
                  </button>
                </td>
                <td>
                     <%= new Date(qrCodesFailed[qr].checkinDate).toLocaleString('en-GB', { day: '2-digit' , month: '2-digit' ,
                                       year: 'numeric' , hour: '2-digit' , minute: '2-digit' , second: '2-digit' , hour12: true
                                       }).replace(',', '' ) %>
                </td>
              </tr>
              <% } %>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <nav id="pagination-nav" aria-label="Page navigation" class="mt-4">
        <ul class="pagination justify-content-center"></ul>
      </nav>

    </div>
  </div>


  <style>
    .filter-and-search-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    .search-bar {
      display: flex;
      gap: 10px;
    }

    .search-bar input {
      padding: 5px 10px;
      font-size: 14px;
      width: 200px;
    }

    .search-bar button {
      padding: 6px 12px;
      font-size: 14px;
      cursor: pointer;
    }

    .filter-section {
      display: flex;
      align-items: center;
      gap: 10px;
      /* Space between the label and dropdown */
    }

    .filter-section label {
      font-size: 14px;
    }

    .filter-section select {
      padding: 5px 10px;
      font-size: 14px;
      width: 180px;
      /* Set width for consistency */
    }
  </style>

  <script>

    let currentPage = 1;
    let keywordFetch = "";
    let roundIdFetch = 0;

    // Function to Change Page
    function changePage(page) {
      if (page < 1 || page === currentPage) return;
      currentPage = page;
      fetchData(page);
    }

    async function fetchData(page = 1) {
      const response = await fetch(`/qrcode/findQRCodeFailedTopupByKeywordForAdmin?keyword=${keywordFetch}&page=${page}`);
      const result = await response.json();
      console.log(result);
      updateTableData(result);
      renderPagination(result.totalPages, page);
    }

     const updateTableData = async (result) => {
          try {
            const data = result.data;
            console.log("Update data ")
            // If data is valid and an array, update the table rows
            if (data && Array.isArray(data)) {
              qrTableBody.innerHTML = data.map(qr => `
                      <tr>
                        <td>${qr.topupTransaction.topupReport.id}</td>
                        <td>${qr.code}</td>
               
                        <td>${qr.topupTransaction.phone}</td>
                        <td>
                           ${qr.topupTransaction.amount.toLocaleString('vi-VN')} VNĐ
                        </td>
                        <td><span class="badge bg-danger">${qr.topupTransaction.topupReport.description === 'Unknow' ?  'Worldsms Không Xác Định' : qr.topupTransaction.topupReport.description}</span></td>
                        <td class="actions">
                          <button class="edit" data-id="${qr.topupTransaction.topupReport.id}">
                              <i class="fa fa-edit"></i>  Gửi lại
                            </button>
                        </td>
                        <td>${new Date(qr.checkinDate).toLocaleString('en-GB', {
                                day: '2-digit',
                                month: '2-digit',
                                year: 'numeric',
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit',
                                hour12: true
                              }).replace(',', '')}
                        </td>

                      </tr>
                    `).join('');
            }
            // Add event listeners for edit buttons
            const editButtons = document.querySelectorAll('.actions .edit');
            editButtons.forEach(button => {
               let isProcessing = false; // 🔒 anti spam
              button.addEventListener('click', async  () => {
                if (isProcessing) return;
                const reportId = button.getAttribute('data-id');
                if (!reportId) return;

                isProcessing = true;
                button.disabled = true;
                button.innerText = 'Processing...';
                try {
                  const res = await fetch('/retry/topup?topUpReportId=' + reportId, {
                    method: 'POST',
                    headers: {
                      'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                      topUpReportId: reportId
                    })
                  });

                  const result = await res.json();

                  if (!res.ok) {
                    throw new Error(result.message || 'Retry failed');
                  }

                  if (result.topUp) {
                    alert('Đã gửi yêu cầu thành công !');
                  } else {
                    alert('Đã gửi yêu cầu và đang trong thời gian xử lý!');
                  }
                } catch (err) {
                  alert(err.message);
                } finally {
                  isProcessing = false;
                  button.disabled = false;
                  button.innerText = 'Retry';
                }
              });
            });
          } catch (error) {
            console.error('Error fetching QR data:', error);
          }
        };

        function renderPagination(totalPages, currentPage) {
          const paginationContainer = document.querySelector('#pagination-nav .pagination');
          paginationContainer.innerHTML = '';

          const maxVisiblePages = 5; // Số nút trang hiển thị xung quanh trang hiện tại
          const startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
          const endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

            // Previous Button
            paginationContainer.innerHTML += `
          <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">Previous</a>
          </li>
          `;

            // First Page Button
            if (startPage > 1) {
              paginationContainer.innerHTML += `
            <li class="page-item">
              <a class="page-link" href="#" onclick="changePage(1)">1</a>
            </li>
            `;
              if (startPage > 2) {
                paginationContainer.innerHTML += `
              <li class="page-item disabled">
                <span class="page-link">...</span>
              </li>
              `;
              }
            }

            // Page Numbers
            for (let i = startPage; i <= endPage; i++) {
              paginationContainer.innerHTML += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
              <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
            </li>
            `;
            }

            // Last Page Button
            if (endPage < totalPages) {
              if (endPage < totalPages - 1) {
                paginationContainer.innerHTML += `
              <li class="page-item disabled">
                <span class="page-link">...</span>
              </li>
              `;
              }
              paginationContainer.innerHTML += `
            <li class="page-item">
              <a class="page-link" href="#" onclick="changePage(${totalPages})">${totalPages}</a>
            </li>
            `;
            }

            // Next Button
            paginationContainer.innerHTML += `
          <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">Next</a>
          </li>
          `;
        }

    document.addEventListener('DOMContentLoaded', () => {
      const searchButton = document.getElementById('searchButton');
      const searchInput = document.getElementById('searchInput');
      const qrTableBody = document.getElementById('qrTableBody');
      const dropdownButton = document.getElementById('dropdownButton');
      const dropdownMenu = document.getElementById('dropdownMenu');

      searchButton.addEventListener('click', () => {
        const searchKeyword = searchInput.value.trim().toLowerCase();
        keywordFetch = searchKeyword;
        currentPage = 1;
        fetchData(currentPage);
      });

      searchInput.addEventListener('keyup', (event) => {
        if (event.key === 'Enter') {
          const searchKeyword = searchInput.value.trim().toLowerCase();
          keywordFetch = searchKeyword;
          currentPage = 1;
          fetchData(currentPage);
        }
      });

      // Fetch Initial Data
      fetchData(currentPage);
    });
  </script>

  <%- include('footer.ejs') %>