@extends('layout.app')
@section('content')
<div class="card">
    <div class="card-header">
        <h3 class="card-title">{{ $page_title }}</h3>
        <div class="card-tools">
            <a href="{{ route('permissions.index') }}" class="btn btn-sm btn-default"><i class="fa fa-arrow-left"></i> Back to Permission List</a>
        </div>
    </div>
    <div class="card-body">
        @if(session('success_message'))
            <div class="alert alert-success">{{ session('success_message') }}</div>
        @endif
        <p class="text-muted mb-3">Permissions are shown by group. Select multiple permissions and use "Move selected to" to change their group, or change the dropdown per row. Then click <strong>Save all changes</strong>.</p>

        <form action="{{ route('permissions.updateGroups') }}" method="POST" id="editGroupsForm">
            @csrf
            @method('PUT')

            @foreach($permissions_grouped as $groupName => $permissions)
            @php $groupSlug = \Illuminate\Support\Str::slug($groupName); @endphp
            <div class="card card-outline card-secondary mb-4 permission-group-block" data-group="{{ $groupSlug }}">
                <div class="card-header py-2 d-flex align-items-center">
                    <div class="custom-control custom-checkbox mr-3">
                        <input type="checkbox" class="custom-control-input group-select-all" id="select-all-{{ $groupSlug }}" data-group="{{ $groupSlug }}" aria-label="Select all in {{ $groupName }}">
                        <label class="custom-control-label font-weight-bold" for="select-all-{{ $groupSlug }}">{{ $groupName }}</label>
                    </div>
                    <span class="badge badge-light">{{ $permissions->count() }} permission(s)</span>
                </div>
                <div class="card-body p-2">
                    <div class="d-flex flex-wrap align-items-center mb-2">
                        <label class="mb-0 mr-2 small text-muted">Move selected to:</label>
                        <select class="form-control form-control-sm select2 move-target-select mr-2" data-group="{{ $groupSlug }}" style="width: 220px;">
                            <option value="">— Choose group —</option>
                            @foreach($groups as $g)
                            @if($g !== $groupName)
                            <option value="{{ $g }}">{{ $g }}</option>
                            @endif
                            @endforeach
                        </select>
                        <button type="button" class="btn btn-sm btn-outline-primary move-selected-btn" data-group="{{ $groupSlug }}">Move selected</button>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered mb-0">
                            <thead class="bg-light">
                                <tr>
                                    <th width="40"><span class="sr-only">Select</span></th>
                                    <th width="60">ID</th>
                                    <th>Permission Name</th>
                                    <th width="260">Group</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($permissions as $p)
                                <tr>
                                    <td class="align-middle">
                                        <input type="checkbox" class="permission-row-check" name="selected[]" value="{{ $p->id }}" data-group="{{ $groupSlug }}" data-permission-id="{{ $p->id }}" aria-label="Select {{ $p->name }}">
                                    </td>
                                    <td>{{ $p->id }}</td>
                                    <td>{{ $p->name }}</td>
                                    <td>
                                        <select name="groups[{{ $p->id }}]" class="form-control form-control-sm select2 permission-group-select" data-permission-id="{{ $p->id }}">
                                            <option value="">— Default (from name) —</option>
                                            @foreach($groups as $group)
                                            <option value="{{ $group }}" @if(($p->group ?: \App\Services\PermissionGroupHelper::getGroupName($p->name)) === $group) selected @endif>{{ $group }}</option>
                                            @endforeach
                                        </select>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            @endforeach

            <div class="form-group mt-3">
                <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Save all changes</button>
                <a href="{{ route('permissions.index') }}" class="btn btn-default">Cancel</a>
            </div>
        </form>
    </div>
</div>

@push('js')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Select2 for group dropdowns
    $('.move-target-select').select2({
        placeholder: '— Choose group —',
        allowClear: true,
        width: '220px'
    });
    $('.permission-group-select').select2({
        placeholder: '— Default (from name) —',
        allowClear: true,
        width: '100%'
    });

    // Select all in group
    document.querySelectorAll('.group-select-all').forEach(function(selectAll) {
        var groupId = selectAll.getAttribute('data-group');
        selectAll.addEventListener('change', function() {
            var block = document.querySelector('.permission-group-block[data-group="' + groupId + '"]');
            if (!block) return;
            block.querySelectorAll('.permission-row-check').forEach(function(cb) {
                cb.checked = selectAll.checked;
            });
        });
    });

    // Move selected: set dropdown for all checked rows in this group to the chosen target group
    document.querySelectorAll('.move-selected-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var groupId = this.getAttribute('data-group');
            var block = document.querySelector('.permission-group-block[data-group="' + groupId + '"]');
            var targetSelect = block && block.querySelector('.move-target-select');
            var targetGroup = targetSelect && $(targetSelect).val();
            if (!targetGroup) {
                alert('Please choose a group first.');
                return;
            }
            block.querySelectorAll('.permission-row-check:checked').forEach(function(cb) {
                var pid = cb.getAttribute('data-permission-id');
                var rowSelect = document.querySelector('.permission-group-select[data-permission-id="' + pid + '"]');
                if (rowSelect) {
                    $(rowSelect).val(targetGroup).trigger('change');
                }
            });
            $(targetSelect).val(null).trigger('change');
        });
    });
});
</script>
@endpush
@endsection
