@extends('layouts.app')
@section('title','Roles & Permissions')
@section('content')
@php
    $filters = [];
    if(request()->filled('search')) $filters[] = ['label'=>'Search','value'=>request('search'),'removeUrl'=>route('admin.roles.index')];
@endphp

<x-ui.page-toolbar title="Roles & Permissions" description="Review protected system roles and maintain auditable custom permission bundles." :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Administration'],['label'=>'Roles & Permissions']]" />

@can('roles.create')
<div class="mb-3 flex justify-end">
    <a class="mf-btn mf-btn-primary" href="{{ route('admin.roles.create') }}">Create custom role</a>
</div>
@endcan

<x-ui.table-toolbar table-id="roles-table" search-placeholder="Search roles…" :columns="['role'=>'Role','permissions'=>'Permissions','users'=>'Users','access'=>'Access']" export-filename="roles.csv" />
<x-ui.applied-filter-chips :filters="$filters" :clear-url="route('admin.roles.index')" />

<div class="mf-table-frame">
<table id="roles-table" class="mf-table" data-standard-table>
<thead><tr><th data-table-column="role">Role</th><th data-table-column="permissions">Permissions</th><th data-table-column="users">Users</th><th data-table-column="access">Access</th><th data-no-export></th></tr></thead>
<tbody>
@forelse($roles as $role)
<tr>
    <td data-table-column="role">
        <span class="font-medium">{{ $role->display_name }}</span>
        <div class="text-xs text-muted-foreground">{{ $role->name }} · {{ $role->is_system ? 'Protected system role' : 'Custom role' }}</div>
    </td>
    <td data-table-column="permissions">{{ $role->permissions_count }}</td>
    <td data-table-column="users">{{ $role->users_count }}</td>
    <td data-table-column="access">{{ $role->name==='super-administrator' ? 'Full system access' : ($role->is_system ? 'Application-managed permissions' : 'Custom assigned permissions') }}</td>
    <td data-no-export class="mf-table-row-actions">
        @if(!$role->is_system)
            @can('roles.update')
                <a class="text-sm text-primary hover:underline" href="{{ route('admin.roles.edit',$role) }}">Edit</a>
            @endcan
            @can('roles.delete')
                <form method="POST" action="{{ route('admin.roles.destroy',$role) }}" class="inline" onsubmit="return confirm('Delete this unused custom role?')">
                    @csrf
                    @method('DELETE')
                    <button class="text-sm text-destructive hover:underline" type="submit" @disabled($role->users_count > 0)>Delete</button>
                </form>
            @endcan
        @else
            <span class="text-xs text-muted-foreground">Locked</span>
        @endif
    </td>
</tr>
@empty<tr><td colspan="5" class="text-center text-muted-foreground">No roles found.</td></tr>@endforelse
</tbody>
</table>
</div>
@endsection
