{% extends "admin_frontend/base.html" %}
{% load breadcrumbs %}
{% block title %}Edit Group Permissions{% endblock %}
{% block content %}
{% render_breadcrumbs breadcrumbs %}
<div class="flex items-center justify-between mb-4">
  <h1 class="text-2xl font-semibold">Edit Permissions — {{ group.name|title }}</h1>
  <a href="{% url 'orgs_admin:permissions_overview' %}" class="btn-outline">Back</a>
</div>

<form method="post" class="space-y-6">
  {% csrf_token %}
{% for app, models in grouped_apps.items %}
  <div class="bg-white rounded shadow p-4" x-data="{ all:false }" data-app="{{ app }}">
    <div class="flex items-center justify-between mb-2">
      <h2 class="font-medium">{{ app|title }}</h2>
      <label class="flex items-center gap-2 text-sm">
        <input type="checkbox" x-model="all" @change="$root.querySelectorAll('[data-app=\'{{ app }}\'] input[name=perm_ids]').forEach(cb=>cb.checked=all)">
        <span>Select all</span>
      </label>
    </div>

    {% for model in models %}
      <div class="mb-3 border-t pt-2" x-data="{ all:false }" data-model="{{ app }}.{{ model.model_key }}">
        <div class="flex items-center justify-between mb-1">
          <h3 class="text-sm font-semibold">{{ model.model_label }}</h3>
          <label class="flex items-center gap-2 text-xs text-gray-600">
            <input type="checkbox" x-model="all" @change="$root.querySelectorAll('[data-model=\'{{ app }}.{{ model.model_key }}\'] input[name=perm_ids]').forEach(cb=>cb.checked=all)">
            <span>Select all {{ model.model_label }}</span>
          </label>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
          {% for p in model.perms %}
            <label class="flex items-center gap-2 text-sm">
              <input type="checkbox" name="perm_ids" value="{{ p.id }}" {% if p.id in current_ids %}checked{% endif %}>
              <span><span class="font-mono text-xs bg-gray-100 px-1 py-0.5 rounded">{{ p.content_type.app_label }}.{{ p.codename }}</span> — {{ p.name }}</span>
            </label>
          {% endfor %}
        </div>
      </div>
    {% endfor %}
  </div>
{% endfor %}
  <div>
    <button class="px-4 py-2 bg-blue-600 text-white rounded">Save Changes</button>
  </div>
</form>
{% endblock %}
