@extends('adminlte::page')

@section('title', 'Edit User')

@section('content_header')
<h1>Edit User: {{ $user->name }}</h1>
@stop

@section('content')

<div class="card">
    <div class="card-body">
        <form method="POST" action="{{ route('admin.users.update', $user->id) }}">
            @csrf
            @method('PUT')

            <div class="form-group">
                <label for="name">Name <span class="text-danger">*</span></label>
                <input type="text"
                       name="name"
                       id="name"
                       class="form-control @error('name') is-invalid @enderror"
                       value="{{ old('name', $user->name) }}"
                       required>
                @error('name')
                    <div class="invalid-feedback">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group">
                <label for="email">Email <span class="text-danger">*</span></label>
                <input type="email"
                       name="email"
                       id="email"
                       class="form-control @error('email') is-invalid @enderror"
                       value="{{ old('email', $user->email) }}"
                       required>
                @error('email')
                    <div class="invalid-feedback">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group">
                <label for="password">New Password</label>
                <input type="password"
                       name="password"
                       id="password"
                       class="form-control @error('password') is-invalid @enderror">
                @error('password')
                    <div class="invalid-feedback">{{ $message }}</div>
                @enderror
                <small class="form-text text-muted">Leave blank to keep current password. Minimum 8 characters if changing.</small>
            </div>

            <div class="form-group">
                <label for="password_confirmation">Confirm New Password</label>
                <input type="password"
                       name="password_confirmation"
                       id="password_confirmation"
                       class="form-control">
            </div>

            <div class="form-group">
                <label>Roles</label>
                <div class="card">
                    <div class="card-body">
                        @forelse($roles as $role)
                        <div class="custom-control custom-checkbox">
                            <input type="checkbox"
                                   class="custom-control-input"
                                   name="roles[]"
                                   value="{{ $role->name }}"
                                   id="role_{{ $role->id }}"
                                   {{ in_array($role->name, old('roles', $userRoles)) ? 'checked' : '' }}>
                            <label class="custom-control-label" for="role_{{ $role->id }}">
                                {{ ucfirst($role->name) }}
                            </label>
                        </div>
                        @empty
                        <p class="text-muted">No roles available</p>
                        @endforelse
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label>Direct Permissions (Optional)</label>
                <small class="form-text text-muted mb-2">Grant specific permissions to this user beyond their role permissions.</small>

                @php
                    $groupedPermissions = $permissions->groupBy(function($permission) {
                        $parts = explode(' ', $permission->name);
                        return $parts[0] ?? 'other';
                    });
                @endphp

                @foreach($groupedPermissions as $category => $perms)
                    <div class="card card-outline card-secondary mb-2">
                        <div class="card-header">
                            <h5 class="card-title">
                                <input type="checkbox" class="select-all-perms" data-category="{{ $category }}">
                                <strong>{{ ucfirst($category) }} Permissions</strong>
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                @foreach($perms as $permission)
                                    <div class="col-md-4 col-sm-6">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox"
                                                   class="custom-control-input permission-checkbox-user perm-category-{{ $category }}"
                                                   name="permissions[]"
                                                   value="{{ $permission->name }}"
                                                   id="permission_{{ $permission->id }}"
                                                   {{ in_array($permission->name, old('permissions', $userPermissions)) ? 'checked' : '' }}>
                                            <label class="custom-control-label" for="permission_{{ $permission->id }}">
                                                {{ $permission->name }}
                                            </label>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> Update User
                </button>
                <a href="{{ route('admin.users.index') }}" class="btn btn-secondary">
                    Cancel
                </a>
            </div>
        </form>
    </div>
</div>

@stop

@section('js')
<script>
    // Select all permissions in a category
    document.querySelectorAll('.select-all-perms').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const category = this.dataset.category;
            const categoryCheckboxes = document.querySelectorAll('.perm-category-' + category);
            categoryCheckboxes.forEach(cb => {
                cb.checked = this.checked;
            });
        });
    });

    // Update "select all" checkbox state when individual checkboxes change
    document.querySelectorAll('.permission-checkbox-user').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const category = this.classList[2].replace('perm-category-', '');
            const allCategoryCheckboxes = document.querySelectorAll('.perm-category-' + category);
            const checkedCategoryCheckboxes = document.querySelectorAll('.perm-category-' + category + ':checked');
            const selectAllCheckbox = document.querySelector('.select-all-perms[data-category="' + category + '"]');

            if (selectAllCheckbox) {
                selectAllCheckbox.checked = allCategoryCheckboxes.length === checkedCategoryCheckboxes.length;
            }
        });
    });

    // Initialize "select all" checkbox states on page load
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.select-all-perms').forEach(selectAllCheckbox => {
            const category = selectAllCheckbox.dataset.category;
            const allCategoryCheckboxes = document.querySelectorAll('.perm-category-' + category);
            const checkedCategoryCheckboxes = document.querySelectorAll('.perm-category-' + category + ':checked');

            if (allCategoryCheckboxes.length === checkedCategoryCheckboxes.length && allCategoryCheckboxes.length > 0) {
                selectAllCheckbox.checked = true;
            }
        });
    });
</script>
@stop
