<%- include('../partials/header') %>
<%- include('../partials/navbar-panitia') %>

<div class="container mt-5">
  <div class="row">
    <div class="col-lg-8">
      <div class="card">
        <div class="card-body">
          <h1 class="card-title mb-4 text-center">Attendance</h1>

          <!-- Flash Messages -->
          <% if (successMessages && successMessages.length > 0) { %>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
              <% successMessages.forEach(message => { %>
                <%= message %><br>
              <% }); %>
              <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
          <% } %>
          <% if (errorMessages && errorMessages.length > 0) { %>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
              <% errorMessages.forEach(message => { %>
                <%= message %><br>
              <% }); %>
              <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
          <% } %>

          <!-- Button to trigger modal for searching guest by name -->
          <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#searchModal">
            Search Guest by Name
          </button>
          <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#addUnregisteredGuestModal">
            Add Unregistered Guest
          </button>

          <!-- Search Modal -->
          <div class="modal fade" id="searchModal" tabindex="-1" aria-labelledby="searchModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="searchModalLabel">Search Guest</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  <form id="search-form">
                    <div class="mb-3">
                      <label for="fullname" class="form-label">Search Guest by Name</label>
                      <input type="text" class="form-control" id="fullname" name="fullname" required>
                    </div>
                    <button type="submit" class="btn btn-secondary">Search</button>
                  </form>
                  <div class="table-responsive">
                    <table class="table table-hover mt-4">
                      <thead class="table-light text-center">
                        <tr>
                          <th>Select</th>
                          <th>Name</th>
                          <th>Phone Number</th>
                          <th>Status</th>
                          <th>Info</th>
                        </tr>
                      </thead>
                      <tbody id="search-results">
                        <!-- Search results will be appended here -->
                      </tbody>
                    </table>
                  </div>
                  <nav aria-label="Search pagination" class="mt-3">
                    <ul class="pagination justify-content-center" id="search-pagination">
                      <!-- Pagination links will be appended here -->
                    </ul>
                  </nav>
                </div>
                <div class="modal-footer">
                  <form action="/panitia/attendance/add" method="POST" id="submit-selected-guest-form">
                    <input type="hidden" name="guest_id" id="guest-id">
                    <button type="submit" class="btn btn-primary">Submit Selected Guest</button>
                  </form>
                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
              </div>
            </div>
          </div>

          <!-- Modal for adding unregistered guest -->
          <div class="modal fade" id="addUnregisteredGuestModal" tabindex="-1" aria-labelledby="addUnregisteredGuestModalLabel" aria-hidden="true">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="addUnregisteredGuestModalLabel">Add Unregistered Guest</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  <form action="/panitia/attendance/addUnregistered" method="POST" id="add-unregistered-guest-form">
                    <div class="mb-3">
                      <label for="unregisteredFullname" class="form-label">Guest Full Name</label>
                      <input type="text" class="form-control" id="unregisteredFullname" name="fullname" required>
                    </div>
                    <div class="mb-3">
                      <label for="unregisteredInfo" class="form-label">Info</label>
                      <input type="text" class="form-control" id="unregisteredInfo" name="info" required>
                    </div>
                    <input type="hidden" name="status" value="tidak-terdaftar">
                    <input type="hidden" name="phone_number" value="">
                    <button type="submit" class="btn btn-primary">Add Unregistered Guest</button>
                  </form>
                </div>
              </div>
            </div>
          </div>

          <!-- Attendance List Table -->
          <div class="table-responsive">
            <table class="table table-hover mt-4 text-center">
              <thead class="table-light text-center">
                <tr>
                  <th>Name</th>
                  <th>Phone Number</th>
                  <th>Status</th>
                  <th>Info</th>
                  <th>Attendance Date</th>
                </tr>
              </thead>
              <tbody id="attendance-list">
                <% attendance.forEach(entry => { %>
                  <tr>
                    <td><%= entry.Guest.fullname %></td>
                    <td><%= entry.Guest.phone_number %></td>
                    <td><%= entry.Guest.status %></td>
                    <td><%= entry.Guest.info %></td>
                    <td><%= entry.attendance_date %></td>
                  </tr>
                <% }) %>
              </tbody>
            </table>
          </div>

          <!-- Pagination controls -->
          <nav aria-label="Page navigation">
            <ul class="pagination justify-content-center">
              <% if (page > 1) { %>
                <li class="page-item">
                  <a class="page-link" href="?page=<%= page - 1 %>&limit=<%= limit %>" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                  </a>
                </li>
              <% } %>
              <% 
                let startPage = Math.max(1, page - 2);
                let endPage = Math.min(totalPages, page + 2);
                if (totalPages > 5) {
                  if (page <= 3) {
                    endPage = 5;
                  } else if (page >= totalPages - 2) {
                    startPage = totalPages - 4;
                  }
                }
              %>
              <% for (let i = startPage; i <= endPage; i++) { %>
                <li class="page-item <%= i === page ? 'active' : '' %>">
                  <a class="page-link" href="?page=<%= i %>&limit=<%= limit %>"><%= i %></a>
                </li>
              <% } %>
              <% if (page < totalPages) { %>
                <li class="page-item">
                  <a class="page-link" href="?page=<%= page + 1 %>&limit=<%= limit %>" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                  </a>
                </li>
              <% } %>
            </ul>
          </nav>
        </div>
      </div>
    </div>

    <!-- QR Code Scanner Card -->
    <div class="col-lg-4">
      <div class="card">
        <div class="card-body">
          <h5 class="card-title">Scan QR Code</h5>
          <div id="qr-reader" style="width: 100%;"></div>
          <div id="qr-reader-results"></div>
        </div>
      </div>
    </div>
  </div>
</div>

<%- include('../partials/footer') %>
<script src="/js/html5-qrcode.min.js" type="text/javascript"></script>
<script>
  document.getElementById('search-form').addEventListener('submit', function(event) {
    event.preventDefault();
    fetchSearchResults(1); // Start with the first page
  });

  function fetchSearchResults(page) {
    const fullname = document.getElementById('fullname').value;
    const searchParams = new URLSearchParams({
      fullname: fullname,
      page: page,
      limit: 5
    });

    fetch('/panitia/attendance/search', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: searchParams.toString(),
    })
    .then(response => response.json())
    .then(data => {
      const searchResults = document.getElementById('search-results');
      searchResults.innerHTML = '';
      if (data.guests.length > 0) {
        data.guests.forEach(guest => {
          const row = `
            <tr>
              <td><input type="radio" name="selectedGuest" value="${guest.guest_id}"></td>
              <td>${guest.fullname}</td>
              <td>${guest.phone_number}</td>
              <td>${guest.status}</td>
              <td>${guest.info}</td>
            </tr>
          `;
          searchResults.insertAdjacentHTML('beforeend', row);
        });
      } else {
        searchResults.insertAdjacentHTML('beforeend', '<tr><td colspan="5" class="text-center">No results found</td></tr>');
      }

      // Update pagination
      const searchPagination = document.getElementById('search-pagination');
      searchPagination.innerHTML = '';

      let startPage = Math.max(1, data.page - 2);
      let endPage = Math.min(data.totalPages, data.page + 2);
      if (data.totalPages > 5) {
        if (data.page <= 3) {
          endPage = 5;
        } else if (data.page >= data.totalPages - 2) {
          startPage = data.totalPages - 4;
        }
      }

      if (data.page > 1) {
        searchPagination.innerHTML += `
          <li class="page-item">
            <a class="page-link" href="#" onclick="fetchSearchResults(${data.page - 1})" aria-label="Previous">
              <span aria-hidden="true">&laquo;</span>
            </a>
          </li>
        `;
      }
      for (let i = startPage; i <= endPage; i++) {
        searchPagination.innerHTML += `
          <li class="page-item ${i === data.page ? 'active' : ''}">
            <a class="page-link" href="#" onclick="fetchSearchResults(${i})">${i}</a>
          </li>
        `;
      }
      if (data.page < data.totalPages) {
        searchPagination.innerHTML += `
          <li class="page-item">
            <a class="page-link" href="#" onclick="fetchSearchResults(${data.page + 1})" aria-label="Next">
              <span aria-hidden="true">&raquo;</span>
            </a>
          </li>
        `;
      }
    })
    .catch(error => console.error('Error:', error));
  }

  document.getElementById('submit-selected-guest-form').addEventListener('submit', function(event) {
    const selectedGuest = document.querySelector('input[name="selectedGuest"]:checked');
    if (!selectedGuest) {
      event.preventDefault();
      alert('Please select a guest.');
    } else {
      document.getElementById('guest-id').value = selectedGuest.value;
    }
  });

  function docReady(fn) {
    if (document.readyState === "complete" || document.readyState === "interactive") {
      setTimeout(fn, 1);
    } else {
      document.addEventListener("DOMContentLoaded", fn);
    }
  }

  docReady(function () {
    var resultContainer = document.getElementById('qr-reader-results');
    var lastResult, countResults = 0;

    function onScanSuccess(qrCodeMessage) {
      if (qrCodeMessage !== lastResult) {
        lastResult = qrCodeMessage;
        console.log(`QR Code Scanned: ${qrCodeMessage}`);

        fetch('/panitia/attendance/addByQRCode', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ guest_id: qrCodeMessage })
        })
        .then(response => response.json())
        .then(data => {
          if (data.redirect) {
            window.location.href = '/panitia/attendance';
          }
        })
        .catch(error => {
          console.error('Error:', error);

          const errorAlert = document.createElement('div');
          errorAlert.className = 'alert alert-danger alert-dismissible fade show';
          errorAlert.role = 'alert';
          errorAlert.innerHTML = `
            An error occurred. Please try again.
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
          `;
          document.body.insertBefore(errorAlert, document.body.firstChild);
        });
      }
    }

    var html5QrcodeScanner = new Html5QrcodeScanner(
      "qr-reader", { fps: 10, qrbox: 250 });
    html5QrcodeScanner.render(onScanSuccess);
  });
</script>
