<div class="modal fade" id="assignRightsModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <form method="POST" action="handlers/assign_rights.php" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Assign Rights to Role</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <div class="mb-3">
          <label for="role" class="form-label">Select Role:</label>
          <select name="role_id" class="form-select" required>
            <option value="">Choose role</option>
            <?php
              include '../db.php';
              $roles = $conn->query("SELECT id, name FROM roles");
              while ($role = $roles->fetch_assoc()) {
                  echo "<option value='{$role['id']}'>{$role['name']}</option>";
              }
            ?>
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label">Select Rights:</label>
          <div class="form-check mb-2">
            <input class="form-check-input" type="checkbox" id="checkAllRights">
            <label class="form-check-label" for="checkAllRights">Check All</label>
          </div>
          <div id="rightsContainer" class="mt-2">
            <!-- Rights checkboxes will be loaded here -->
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button type="submit" class="btn btn-success">Assign Rights</button>
      </div>
    </form>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const roleSelect = document.querySelector('#assignRightsModal select[name="role_id"]');
  const rightsContainer = document.getElementById('rightsContainer');
  const checkAllBox = document.getElementById('checkAllRights');

  if (roleSelect) {
    roleSelect.addEventListener('change', function () {
      const roleId = this.value;
      console.log('Role selected:', roleId);
      
      if (!roleId) {
        rightsContainer.innerHTML = '';
        return;
      }

      // Show loading
      rightsContainer.innerHTML = '<div class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading rights...</div>';

      fetch(`handlers/fetch_rights.php?role_id=${roleId}`)
        .then(res => res.json())
        .then(data => {
          console.log('Rights data:', data);
          const assignedRights = new Set(data.assigned.map(id => id.toString()));
          rightsContainer.innerHTML = '';

          for (const [category, rights] of Object.entries(data.grouped)) {
            rightsContainer.innerHTML += `
              <div class="mb-4">
                <h6 class="text-primary mb-3">${category}</h6>
            `;
            
            rights.forEach(right => {
              const checked = assignedRights.has(right.id.toString()) ? 'checked' : '';
              rightsContainer.innerHTML += `
                <div class="form-check mb-2">
                  <input class="form-check-input" type="checkbox" name="rights[]" value="${right.id}" id="right${right.id}" ${checked}>
                  <label class="form-check-label" for="right${right.id}">${right.name}</label>
                </div>
              `;
            });
            
            rightsContainer.innerHTML += `</div>`;
          }
        })
        .catch(error => {
          console.error('Error loading rights:', error);
          rightsContainer.innerHTML = '<div class="alert alert-danger">Error loading rights. Please try again.</div>';
        });
    });
  }

  if (checkAllBox) {
    checkAllBox.addEventListener('change', function () {
      const allBoxes = rightsContainer.querySelectorAll('input[type="checkbox"]');
      allBoxes.forEach(box => box.checked = this.checked);
    });
  }
});
</script>
