@csrf
@php $isSuper = ($role->name ?? null) === \App\Models\User::SUPER_ADMIN; @endphp

<div class="row g-3 mb-3">
    <div class="col-md-6">
        <label class="form-label">Role Name <span class="text-danger">*</span></label>
        <input type="text" name="name" value="{{ old('name', $role->name) }}" class="form-control @error('name') is-invalid @enderror" {{ $isSuper ? 'readonly' : '' }} required>
        @error('name')<div class="invalid-feedback">{{ $message }}</div>@enderror
    </div>
</div>

<div class="card border">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span><i class="bi bi-key me-1"></i>Permissions</span>
        <div class="form-check mb-0">
            <input class="form-check-input" type="checkbox" id="check-all">
            <label class="form-check-label small" for="check-all">Select all</label>
        </div>
    </div>
    <div class="card-body">
        <div class="row g-3">
            @foreach($grouped as $module => $permissions)
                <div class="col-md-6 col-xl-4">
                    <div class="border rounded p-3 h-100">
                        <div class="fw-semibold text-capitalize mb-2">
                            <i class="bi bi-folder me-1 text-muted"></i>{{ str_replace('_', ' ', $module) }}
                        </div>
                        @foreach($permissions as $permission)
                            <div class="form-check">
                                <input class="form-check-input perm-check" type="checkbox" name="permissions[]"
                                       value="{{ $permission->name }}" id="perm-{{ $permission->id }}"
                                       @checked(in_array($permission->name, old('permissions', $assigned)))>
                                <label class="form-check-label small" for="perm-{{ $permission->id }}">
                                    {{ ucfirst(explode('.', $permission->name)[1]) }}
                                </label>
                            </div>
                        @endforeach
                    </div>
                </div>
            @endforeach
        </div>
    </div>
</div>

<div class="mt-4 d-flex gap-2">
    <button class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>{{ $submitLabel ?? 'Save' }}</button>
    <a href="{{ route('roles.index') }}" class="btn btn-light border">Cancel</a>
</div>

@push('scripts')
<script>
    document.getElementById('check-all').addEventListener('change', function (e) {
        document.querySelectorAll('.perm-check').forEach(c => c.checked = e.target.checked);
    });
</script>
@endpush
