{{-- resources/views/admin/roles/create.blade.php --}}
@extends('layouts.app')

@section('heading')
<div class="page-heading">
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item">
                <a href="{{ route('admin.dashboard') }}">Tableau de bord</a>
            </li>
            <li class="breadcrumb-item">
                <a href="{{ route('roles.index') }}">Rôles</a>
            </li>
            <li class="breadcrumb-item active" aria-current="page">Modifier</li>
        </ol>
    </nav>
    <h3>Modifier un rôle
        <a href="{{ route('roles.index') }}" class="btn btn-secondary float-end">
                        <i class="bi bi-arrow-left"></i> Retour
                    </a>

    </h3>
</div>
@endsection
@section('content')
    <div class="card">


        <form method="POST" action="{{ route('roles.update', $role->id) }}">
            @csrf
            @method('PUT')
            <div class="card-body">
                <!-- Nom du rôle -->
                <div class="form-group">
                    <label for="name" class="required">Nom du rôle</label>
                    <input type="text" 
                            class="form-control @error('name') is-invalid @enderror" 
                            id="name" 
                            name="name" 
                            value="{{ $role->name }}" 
                            required
                            placeholder="Ex: manager, editor, viewer">
                    @error('name')
                    <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                    <small class="form-text text-muted">
                        Le nom doit être unique et en minuscules (ex: manager, editor)
                    </small>
                </div>

                <!-- Sélection des permissions -->
                <div class="form-group">
                    <label>Permissions</label>
                    <div class="row">
                        <div class="col-12 mb-3">
                            <button type="button" class="btn btn-sm btn-outline-primary" id="selectAll">
                                <i class="bi bi-check-square"></i> Tout sélectionner
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-secondary ml-2" id="deselectAll">
                                <i class="bi bi-square"></i> Tout désélectionner
                            </button>
                        </div>
                        
                        @php
                            $groupedPermissions = $permissions->groupBy(function ($permission) {
                                return explode('-', $permission->name)[0];
                            });
                        @endphp

                        @foreach($groupedPermissions as $group => $groupPermissions)
                        <div class="col-md-6 mb-4">
                            <div class="card">
                                <div class="card-header bg-light">
                                    <h6 class="mb-0">
                                        <i class="bi bi-{{ $group == 'user' ? 'users' : ($group == 'role' ? 'user-tag' : 'key') }}"></i>
                                        Permissions {{ ucfirst($group) }}
                                        <button type="button" class="btn btn-xs btn-outline-info ml-2 group-toggle" data-group="{{ $group }}">
                                            <i class="bi bi-check"></i> Tout
                                        </button>
                                    </h6>
                                </div>
                                <div class="card-body">
                                    @foreach($groupPermissions as $permission)
                                    <div class="form-check mb-2">
                                        <input type="checkbox" 
                                                class="form-check-input permission-checkbox group-{{ $group }}" 
                                                id="permission_{{ $permission->id }}" 
                                                name="permissions[]" 
                                                value="{{ $permission->name }}"
                                                {{ in_array($permission->name,  $role->permissions->pluck('name')->toArray()??[]) ? 'checked' : '' }}>
                                        <label class="form-check-label" for="permission_{{ $permission->id }}">
                                            <strong>{{ ucfirst(str_replace('-', ' ', $permission->name)) }}</strong>
                                            @php
                                                $action = explode('-', $permission->name)[1] ?? '';
                                                $descriptions = [
                                                    'list' => 'Afficher la liste',
                                                    'create' => 'Créer de nouveaux éléments',
                                                    'edit' => 'Modifier les éléments existants',
                                                    'delete' => 'Supprimer les éléments',
                                                    'logs' => 'Gérer les logs',
                                                    'impersonate' => 'Se faire passer pour un utilisateur',
                                                    'change-password' => 'Changer le mot de passe',
                                                    'assign' => 'Attribuer des rôles',
                                                    'revoke' => 'Révoquer des rôles',
                                                    'approve' => 'Approuver un élément',
                                                    'reject' => 'Rejeter un élément',
                                                    'export' => 'Exporter des éléments',
                                                    'show' => 'Afficher un élément',
                                                ];
                                            @endphp
                                            @if(isset($descriptions[$action]))
                                            <br><small class="text-muted">{{ $descriptions[$action] }}</small>
                                            @endif
                                        </label>
                                    </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                        @endforeach
                    </div>
                    @error('permissions')
                    <div class="text-danger">{{ $message }}</div>
                    @enderror
                </div>
            </div>

            <div class="card-footer text-end">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save"></i> Enregistrer le rôle
                </button>
                <a href="{{ route('roles.index') }}" class="btn btn-secondary ml-2">
                    Annuler
                </a>
            </div>
        </form>
    </div>
@endsection

@push('styles')
<style>
.required:after {
    content: " *";
    color: red;
}
.card-header h6 {
    color: #495057;
}
</style>
@endpush

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Sélectionner/Désélectionner tout
    document.getElementById('selectAll').addEventListener('click', function() {
        document.querySelectorAll('.permission-checkbox').forEach(function(checkbox) {
            checkbox.checked = true;
        });
    });

    document.getElementById('deselectAll').addEventListener('click', function() {
        document.querySelectorAll('.permission-checkbox').forEach(function(checkbox) {
            checkbox.checked = false;
        });
    });

    // Sélectionner par groupe
    document.querySelectorAll('.group-toggle').forEach(function(button) {
        button.addEventListener('click', function() {
            const group = this.dataset.group;
            const checkboxes = document.querySelectorAll('.group-' + group);
            const allChecked = Array.from(checkboxes).every(cb => cb.checked);
            
            checkboxes.forEach(function(checkbox) {
                checkbox.checked = !allChecked;
            });
        });
    });
});
</script>
@endpush