<x-app-layout>
    <x-slot name="header">
        <div class="d-flex align-items-center justify-content-between gap-3">
            <h2 class="h4 mb-0">Role Management</h2>
            <div class="d-flex flex-wrap gap-2">
                <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#permissionModal"><i data-feather="key"></i> Custom Permission</button>
                <a href="{{ route('admin.roles.create') }}" class="btn btn-primary"><i data-feather="plus"></i> Custom Role</a>
            </div>
        </div>
    </x-slot>

    <div class="row g-3 mb-4">
        <div class="col-6 col-lg-3"><div class="card h-100"><div class="card-body"><small class="text-muted">Total Roles</small><div class="stat-value">{{ $roles->count() }}</div></div></div></div>
        <div class="col-6 col-lg-3"><div class="card h-100"><div class="card-body"><small class="text-muted">Permissions</small><div class="stat-value">{{ $permissions->count() }}</div></div></div></div>
        <div class="col-6 col-lg-3"><div class="card h-100"><div class="card-body"><small class="text-muted">Custom Roles</small><div class="stat-value">{{ $roles->whereNotIn('name', ['Super Admin', 'Admin'])->count() }}</div></div></div></div>
        <div class="col-6 col-lg-3"><div class="card h-100"><div class="card-body"><small class="text-muted">Custom Permissions</small><div class="stat-value">{{ $permissions->whereNotIn('name', $systemPermissionNames)->count() }}</div></div></div></div>
    </div>

    <div class="card shadow-sm border-0 mb-4">
        <div class="card-header d-flex align-items-center justify-content-between"><span>Roles</span><small class="text-muted">Create a role, then select Customer, Billing, MikroTik or other permissions.</small></div>
        <div class="card-body"><div class="table-responsive"><table class="table table-hover align-middle"><thead><tr><th>Role</th><th>Staff</th><th>Permissions</th><th>Type</th><th class="text-end">Action</th></tr></thead><tbody>
            @foreach($roles as $role)
                @php $protected = in_array($role->name, ['Super Admin', 'Admin'], true); @endphp
                <tr><td class="fw-semibold">{{ $role->name }}</td><td>{{ $role->users_count }}</td><td><span class="badge bg-primary-subtle text-primary">{{ $role->name === 'Super Admin' ? 'All' : $role->permissions_count }}</span></td><td><span class="badge {{ $protected ? 'bg-secondary' : 'bg-success' }}">{{ $protected ? 'Protected' : 'Manageable' }}</span></td><td class="text-end">
                    @unless($protected)<div class="btn-group"><a href="{{ route('admin.roles.edit', $role) }}" class="btn btn-sm btn-outline-primary">Edit Permissions</a><button type="button" class="btn btn-sm btn-outline-danger delete-role" data-url="{{ route('admin.roles.destroy', $role) }}" data-name="{{ $role->name }}">Delete</button></div>@endunless
                </td></tr>
            @endforeach
        </tbody></table></div></div>
    </div>

    <div class="card shadow-sm border-0">
        <div class="card-header"><span>Permission Directory</span></div>
        <div class="card-body">
            <div class="alert alert-info py-2 px-3">System permissions already protect their matching pages and actions. Custom permissions are available for custom features/extensions that check the same permission name.</div>
            <div class="d-flex flex-wrap gap-2">
                @foreach($permissions as $permission)
                    @php $system = $systemPermissionNames->contains($permission->name); @endphp
                    <span class="d-inline-flex align-items-center gap-2 border rounded-pill px-3 py-2 bg-light">
                        <code>{{ $permission->name }}</code>
                        <small class="text-muted">{{ $system ? 'System' : 'Custom' }}</small>
                        @unless($system)
                            <button type="button" class="btn btn-link text-danger p-0 delete-permission" aria-label="Delete permission" data-url="{{ route('admin.roles.permissions.destroy', $permission) }}" data-name="{{ $permission->name }}"><i class="fas fa-times"></i></button>
                        @endunless
                    </span>
                @endforeach
            </div>
        </div>
    </div>

    <div class="modal fade" id="permissionModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><form id="permissionForm" action="{{ route('admin.roles.permissions.store') }}" method="POST">@csrf<div class="modal-header"><h2 class="modal-title h5">Create Custom Permission</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><label class="form-label" for="permissionName">Permission Name</label><input id="permissionName" name="name" class="form-control" required maxlength="125" pattern="[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+" placeholder="example: customer.approve"><div class="form-text">Use lowercase <strong>module.action</strong> format. After creating it, assign it from a Role form.</div></div><div class="modal-footer"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary" id="savePermissionButton">Create Permission</button></div></form></div></div></div>

    @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                $(document).on('click', '.delete-role', function () {
                    const button = $(this);
                    Swal.fire({title:'Delete role?',text:button.data('name')+' will be permanently removed.',icon:'warning',showCancelButton:true,confirmButtonText:'Yes, delete',confirmButtonColor:'#dc3545'}).then(result => {
                        if (!result.isConfirmed) return;
                        button.prop('disabled', true);
                        axios.delete(button.data('url')).then(response => { button.closest('tr').remove(); showToast(response.data.message, 'success'); }).catch(error => { button.prop('disabled', false); showToast(error.response?.data?.message || 'Role could not be deleted.', 'error'); });
                    });
                });

                $('#permissionForm').on('submit', function (event) {
                    event.preventDefault();
                    const form = $(this), button = $('#savePermissionButton');
                    button.prop('disabled', true);
                    $.post(form.attr('action'), form.serialize()).done(response => { showToast(response.message, 'success'); window.location.reload(); }).fail(xhr => { button.prop('disabled', false); handleFormErrors(xhr, form); });
                });

                $(document).on('click', '.delete-permission', function () {
                    const button = $(this);
                    Swal.fire({title:'Delete custom permission?',text:button.data('name'),icon:'warning',showCancelButton:true,confirmButtonText:'Delete',confirmButtonColor:'#dc3545'}).then(result => {
                        if (!result.isConfirmed) return;
                        axios.delete(button.data('url')).then(response => { button.closest('span').remove(); showToast(response.data.message, 'success'); }).catch(error => showToast(error.response?.data?.message || 'Permission could not be deleted.', 'error'));
                    });
                });
            });
        </script>
    @endpush
</x-app-layout>
