<script>
const sidebar = document.getElementById('sidebar');
const body = document.body;

document.getElementById('toggleSidebar').addEventListener('click', function() {
    sidebar.classList.add('active');
    body.classList.add('sidebar-open');
});
document.getElementById('closeSidebar').addEventListener('click', function() {
    sidebar.classList.remove('active');
    body.classList.remove('sidebar-open');
});
</script>
<!-- Assign Card Modal -->
<div class="modal fade" id="assignNfcModal" tabindex="-1" aria-labelledby="assignNfcLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content text-start">
      <div class="modal-header">
        <h5 class="modal-title" id="assignNfcLabel">Assign Card to <span id="assignMemberName"></span></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="assignMemberId">
        <label>Scan NFC card:</label>
        <input type="text" id="assignCardInput" class="form-control" placeholder="Scan card...">
        <div class="mt-3 text-success" id="assignSuccess" style="display:none;"></div>
        <div class="mt-2 text-danger" id="assignError" style="display:none;"></div>
        <button type="button" id="removeCardBtn" class="btn btn-outline-danger mt-3" style="display:none;">
  Remove Assigned Card
</button>

      </div>
    </div>
  </div>
</div>
<!-- Scan Member Modal -->
<div class="modal fade" id="scanModal" tabindex="-1" aria-labelledby="scanModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content text-center">
      <div class="modal-header">
        <h5 class="modal-title" id="scanModalLabel">Scan Member</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3 align-items-center">
          <!-- Photo -->
          <div class="col-md-4 text-center">
            <img id="memberPhoto" src="" alt="Member Photo" class="img-fluid rounded border" style="max-height: 180px; display: none;">
          </div>

          <!-- Info -->
          <div class="col-md-8 text-start">
            <div id="memberInfo">
              <p><strong>Name:</strong> <span id="memberName">Waiting...</span></p>
              <p><strong>Status:</strong> <span id="memberStatus"></span></p>
              <p><strong>Expiry:</strong> <span id="memberExpiry"></span></p>
              <p><strong>Phone:</strong> <span id="memberPhone"></span></p>
              <p><strong>Action:</strong> <span id="memberAction" class="fw-bold text"></span></p>
            </div>

            <input type="text" id="nfcInput" class="form-control mt-3" placeholder="Scan card..." autofocus>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>


<script>
document.addEventListener('DOMContentLoaded', function () {
  // === SCAN MEMBER MODAL ===
  const input = document.getElementById('nfcInput');
  const name = document.getElementById('memberName');
  const status = document.getElementById('memberStatus');
  const expiry = document.getElementById('memberExpiry');
  const phone = document.getElementById('memberPhone');
  const photo = document.getElementById('memberPhoto');
  const action = document.getElementById('memberAction');
  const scanModal = document.getElementById('scanModal');
  const modalContent = scanModal.querySelector('.modal-content');
  let scanTimer = null;
  let isScanning = false;

  scanModal.addEventListener('shown.bs.modal', () => {
    input.value = '';
    name.innerText = 'Waiting...';
    status.innerText = '';
    expiry.innerText = '';
    phone.innerText = '';
    action.innerText = '';
    photo.style.display = 'none';
    modalContent.classList.remove('bg-danger', 'text-white'); // reset color
    isScanning = false;
    input.focus();
  });

  input.addEventListener('input', () => {
    if (isScanning) return;
    clearTimeout(scanTimer);
    scanTimer = setTimeout(() => {
      const uid = input.value.trim();
      if (uid.length >= 8) {
        isScanning = true;
        fetch('scan_process.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: 'uid=' + encodeURIComponent(uid)
        })
        .then(res => res.json())
        .then(data => {
          if (data.success) {
            name.innerText = data.name;
            status.innerText = data.status;
            expiry.innerText = data.expiry;
            phone.innerText = data.phone;
            action.innerText = data.message;
            action.className = 'fw-bold ' + (data.action === 'login' ? 'text-success' : 'text-danger');
photo.src = 'uploads/' + (data.photo || 'default.png');
photo.onerror = function() {
  this.onerror = null;
  this.src = 'uploads/default.png';
};
            photo.style.display = 'block';

            // Make modal red if expired
            // Reset classes first
modalContent.classList.remove('bg-danger', 'bg-warning', 'bg-success', 'text-white');

// Apply color based on status
switch (data.status.toLowerCase()) {
  case 'expired':
    modalContent.classList.add('bg-danger', 'text-white');
    break;
  case 'due':
    modalContent.classList.add('bg-warning');
    break;
  case 'ok':
    modalContent.classList.add('bg-success', 'text-white');
    break;
}

          } else {
            name.innerText = data.message;
            status.innerText = '';
            expiry.innerText = '';
            phone.innerText = '';
            action.innerText = '';
            photo.style.display = 'none';
            modalContent.classList.remove('bg-danger', 'text-white');
          }
          input.value = '';
          isScanning = false;
        })
        .catch(() => {
          name.innerText = 'Error contacting server';
          isScanning = false;
          modalContent.classList.remove('bg-danger', 'text-white');
        });
      }
    }, 250);
  });

  // === ASSIGN CARD MODAL ===
  const assignBtns = document.querySelectorAll('.assign-btn');
  const assignInput = document.getElementById('assignCardInput');
  const assignId = document.getElementById('assignMemberId');
  const assignName = document.getElementById('assignMemberName');
  const assignSuccess = document.getElementById('assignSuccess');
  const assignError = document.getElementById('assignError');
  const assignModal = document.getElementById('assignNfcModal');
  const removeCardBtn = document.getElementById('removeCardBtn');

  assignBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      const memberId = btn.getAttribute('data-member-id');
      const memberName = btn.getAttribute('data-member-name');
      const existingUid = btn.getAttribute('data-uid');

      assignId.value = memberId;
      assignName.textContent = memberName;
      assignInput.value = existingUid || '';
      assignSuccess.style.display = 'none';
      assignError.style.display = 'none';

      if (existingUid) {
        removeCardBtn.style.display = 'inline-block';
      } else {
        removeCardBtn.style.display = 'none';
      }

      const modal = new bootstrap.Modal(assignModal);
      modal.show();
      setTimeout(() => assignInput.focus(), 500);
    });
  });

  assignInput.addEventListener('input', () => {
    const uid = assignInput.value.trim();
    const memberId = assignId.value;

    if (uid.length >= 8) {
      fetch('assign_card.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'uid=' + encodeURIComponent(uid) + '&member_id=' + encodeURIComponent(memberId)
      })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          assignError.style.display = 'none';
          assignSuccess.textContent = data.message;
          assignSuccess.style.display = 'block';
          assignInput.value = '';
          removeCardBtn.style.display = 'inline-block';

          const btn = document.querySelector(`.assign-btn[data-member-id="${memberId}"]`);
          btn.textContent = 'Card Assigned';
          btn.classList.remove('btn-primary');
          btn.classList.add('btn-success');
          btn.setAttribute('data-uid', data.uid);
        } else {
          assignSuccess.style.display = 'none';
          assignError.textContent = data.message || 'Error';
          assignError.style.display = 'block';
        }
      });
    }
  });

  removeCardBtn.addEventListener('click', () => {
    const memberId = assignId.value;
    if (!confirm('Are you sure you want to unassign the card from this member?')) return;

    fetch('unassign_card.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: 'member_id=' + encodeURIComponent(memberId)
    })
    .then(res => res.text())
    .then(response => {
      assignSuccess.textContent = response;
      assignSuccess.style.display = 'block';
      assignInput.value = '';
      removeCardBtn.style.display = 'none';

      const btn = document.querySelector(`.assign-btn[data-member-id="${memberId}"]`);
      btn.textContent = 'Assign Card';
      btn.classList.remove('btn-success');
      btn.classList.add('btn-primary');
      btn.removeAttribute('data-uid');
    });
  });
});
</script>




<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

