@extends('layouts.admin-simple')

@section('title', 'Edit Role')
@section('page-title', 'Edit Role')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="{{ route('admin.roles') }}">Roles</a></li>
    <li class="breadcrumb-item active" aria-current="page">Edit Role</li>
@endsection

@section('content')
    <form method="POST" action="{{ route('admin.roles.update', $role) }}" id="editRoleForm">
        @csrf
        @method('PUT')
        
        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-white">
                        <h4 class="card-header__title">Role Details</h4>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label for="name">Role Name</label>
                            <input type="text" class="form-control" id="name" value="{{ $role->name }}" disabled>
                            <small class="form-text text-muted">Role name cannot be changed after creation</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="display_name">Display Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control @error('display_name') is-invalid @enderror" 
                                   id="display_name" name="display_name" 
                                   value="{{ old('display_name', $role->display_name) }}" required>
                            @error('display_name')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        
                        <div class="form-group">
                            <label for="description">Description</label>
                            <textarea class="form-control @error('description') is-invalid @enderror" 
                                      id="description" name="description" rows="3">{{ old('description', $role->description) }}</textarea>
                            @error('description')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        
                        <div class="form-group">
                            <div class="custom-control custom-switch">
                                <input type="checkbox" class="custom-control-input" id="is_active" 
                                       name="is_active" value="1"
                                       {{ old('is_active', $role->is_active) ? 'checked' : '' }}>
                                <label class="custom-control-label" for="is_active">Role is Active</label>
                                <small class="form-text text-muted">Inactive roles cannot be assigned to users</small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card mt-3">
                    <div class="card-header bg-white">
                        <h4 class="card-header__title">Permissions</h4>
                        <div class="card-subtitle text-muted">Select permissions for this role</div>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectAll()">Select All</button>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="deselectAll()">Deselect All</button>
                            <span class="ml-3 text-muted">
                                <span id="selectedCount">0</span> permissions selected
                            </span>
                        </div>
                        
                        @foreach($permissions as $group => $groupPermissions)
                        <div class="permission-group mb-4">
                            <h6 class="text-uppercase text-muted mb-3">
                                <i class="material-icons mr-1" style="font-size: 18px;">folder</i>
                                {{ ucfirst(str_replace('_', ' ', $group)) }}
                                <button type="button" class="btn btn-sm btn-link" 
                                        onclick="toggleGroup('{{ $group }}')">Toggle Group</button>
                            </h6>
                            <div class="row">
                                @foreach($groupPermissions as $permission)
                                <div class="col-md-6 col-lg-4">
                                    <div class="custom-control custom-checkbox mb-2">
                                        <input type="checkbox" class="custom-control-input permission-checkbox" 
                                               id="permission_{{ $permission->id }}" 
                                               name="permissions[]" 
                                               value="{{ $permission->id }}"
                                               data-group="{{ $group }}"
                                               {{ in_array($permission->id, old('permissions', $rolePermissions)) ? 'checked' : '' }}>
                                        <label class="custom-control-label" for="permission_{{ $permission->id }}">
                                            {{ $permission->display_name }}
                                            @if($permission->description)
                                                <i class="material-icons text-muted" style="font-size: 14px;" 
                                                   data-toggle="tooltip" title="{{ $permission->description }}">info</i>
                                            @endif
                                        </label>
                                    </div>
                                </div>
                                @endforeach
                            </div>
                        </div>
                        @endforeach
                    </div>
                </div>
                
                <div class="card-footer bg-white">
                    <a href="{{ route('admin.roles') }}" class="btn btn-secondary">
                        <i class="material-icons mr-2">arrow_back</i> Cancel
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="material-icons mr-2">save</i> Update Role
                    </button>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header bg-white">
                        <h5 class="card-header__title">Role Information</h5>
                    </div>
                    <div class="card-body">
                        <dl class="row">
                            <dt class="col-sm-6">Role Name:</dt>
                            <dd class="col-sm-6">{{ $role->name }}</dd>
                            
                            <dt class="col-sm-6">Created:</dt>
                            <dd class="col-sm-6">{{ $role->created_at->format('M d, Y') }}</dd>
                            
                            <dt class="col-sm-6">Last Updated:</dt>
                            <dd class="col-sm-6">{{ $role->updated_at->format('M d, Y') }}</dd>
                            
                            <dt class="col-sm-6">Assigned Users:</dt>
                            <dd class="col-sm-6">
                                <span class="badge badge-info">{{ $role->users()->count() }} users</span>
                            </dd>
                            
                            <dt class="col-sm-6">Status:</dt>
                            <dd class="col-sm-6">
                                @if($role->is_active)
                                    <span class="badge badge-success">Active</span>
                                @else
                                    <span class="badge badge-danger">Inactive</span>
                                @endif
                            </dd>
                        </dl>
                        
                        @if(in_array($role->name, ['super_admin', 'admin', 'hr_manager', 'viewer']))
                        <div class="alert alert-info">
                            <i class="material-icons">info</i>
                            This is a system role. Some restrictions may apply.
                        </div>
                        @endif
                    </div>
                </div>
                
                @if($role->users()->count() > 0)
                <div class="card mt-3">
                    <div class="card-header bg-white">
                        <h5 class="card-header__title">Users with this Role</h5>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled">
                            @foreach($role->users()->limit(5)->get() as $user)
                            <li class="mb-2">
                                <i class="material-icons" style="font-size: 16px;">person</i>
                                {{ $user->full_name }}
                            </li>
                            @endforeach
                            @if($role->users()->count() > 5)
                            <li class="text-muted">
                                and {{ $role->users()->count() - 5 }} more...
                            </li>
                            @endif
                        </ul>
                    </div>
                </div>
                @endif
            </div>
        </div>
    </form>
@endsection

@push('scripts')
<script>
function selectAll() {
    document.querySelectorAll('.permission-checkbox').forEach(checkbox => {
        checkbox.checked = true;
    });
    updateSelectedCount();
}

function deselectAll() {
    document.querySelectorAll('.permission-checkbox').forEach(checkbox => {
        checkbox.checked = false;
    });
    updateSelectedCount();
}

function toggleGroup(group) {
    const groupCheckboxes = document.querySelectorAll(`.permission-checkbox[data-group="${group}"]`);
    const allChecked = Array.from(groupCheckboxes).every(cb => cb.checked);
    
    groupCheckboxes.forEach(checkbox => {
        checkbox.checked = !allChecked;
    });
    updateSelectedCount();
}

function updateSelectedCount() {
    const checkedCount = document.querySelectorAll('.permission-checkbox:checked').length;
    document.getElementById('selectedCount').textContent = checkedCount;
}

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();
    
    // Update count on page load
    updateSelectedCount();
    
    // Add event listeners to checkboxes
    document.querySelectorAll('.permission-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', updateSelectedCount);
    });
});
</script>
@endpush