@extends('adminlte::page')

@section('title', 'Roles & Permissions')

@section('content_header')
    <div class="d-flex justify-content-between">
        <h1><i class="fas fa-user-shield mr-2"></i>Police Ranks & Access Control</h1>
        <div>
            <button class="btn btn-sm btn-outline-info" data-toggle="modal" data-target="#rankInfoModal">
                <i class="fas fa-info-circle mr-1"></i> About Police Ranks
            </button>
        </div>
    </div>
@stop

@section('content')
<div class="row">
    <div class="col-md-12">
        @if(session('success'))
            <div class="alert alert-success alert-dismissible">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                <h5><i class="icon fas fa-check"></i> Success!</h5>
                {{ session('success') }}
            </div>
        @endif
        
        @if(session('error'))
            <div class="alert alert-danger alert-dismissible">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                <h5><i class="icon fas fa-ban"></i> Error!</h5>
                {{ session('error') }}
            </div>
        @endif
        
        <div class="card card-primary card-outline">
            <div class="card-header">
                <h3 class="card-title">Police Ranks & Access Control</h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-info btn-sm mr-2" data-toggle="modal" data-target="#rankInfoModal" title="Learn about police ranks">
                        <i class="fas fa-info-circle mr-1"></i> Rank System Info
                    </button>
                    <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#createRoleModal">
                        <i class="fas fa-plus mr-1"></i> Create New Role
                    </button>
                    <button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Rank/Role Name</th>
                                <th>Rank Level</th>
                                <th>Jurisdiction</th>
                                <th>Permissions</th>
                                <th>Users Count</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($roles as $role)
                                <tr>
                                    <td>{{ $role->name }}</td>
                                    <td>
                                        <div style="max-height: 100px; overflow-y: auto;">
                                            @php
                                                // Group permissions by their prefix (module)
                                                $groupedPermissions = $role->permissions->groupBy(function($permission) {
                                                    $parts = explode('.', $permission->name);
                                                    return count($parts) > 1 ? $parts[0] : 'general';
                                                });
                                            @endphp
                                            
                                            @foreach($groupedPermissions as $group => $permissions)
                                                <div class="mb-1">
                                                    <span class="badge badge-secondary">{{ ucfirst($group) }}</span>
                                                    @foreach($permissions as $permission)
                                                        <span class="badge badge-info mr-1" title="{{ $permission->name }}">
                                                            {{ str_replace($group.'.', '', $permission->name) }}
                                                        </span>
                                                    @endforeach
                                                </div>
                                            @endforeach
                                        </div>
                                    </td>
                                    <td>{{ \App\Models\User::role($role->name)->count() }}</td>
                                    <td>
                                        <div class="btn-group">
                                            <button type="button" class="btn btn-sm btn-warning" data-toggle="modal" data-target="#editRoleModal{{ $role->id }}" title="Edit Role">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#deleteRoleModal{{ $role->id }}" title="Delete Role">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-info" title="View Users with this Role" onclick="window.location.href='{{ route("users.index") }}?role={{ $role->name }}'">
                                                <i class="fas fa-users"></i>
                                            </button>
                                        </div>
                                        
                                        <!-- Edit Role Modal -->
                                        <div class="modal fade" id="editRoleModal{{ $role->id }}">
                                            <div class="modal-dialog modal-lg">
                                                <div class="modal-content">
                                                    <div class="modal-header bg-primary">
                                                        <h4 class="modal-title">Edit Role: {{ $role->name }}</h4>
                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                            <span aria-hidden="true">&times;</span>
                                                        </button>
                                                    </div>
                                                    <form action="{{ route('settings.update-role', $role->id) }}" method="POST">
                                                        @csrf
                                                        <div class="modal-body">
                                                            <div class="form-group">
                                                                <label for="name{{ $role->id }}">Role Name</label>
                                                                <input type="text" class="form-control" id="name{{ $role->id }}" name="name" value="{{ $role->name }}" required>
                                                            </div>
                                                            
                                                            <div class="form-group">
                                                                <label>Permissions</label>
                                                                <p class="text-muted">Select the permissions to assign to this role</p>
                                                                
                                                                <div class="mb-2">
                                                                    <button type="button" class="btn btn-xs btn-outline-primary select-all-permissions-{{ $role->id }}">Select All</button>
                                                                    <button type="button" class="btn btn-xs btn-outline-secondary deselect-all-permissions-{{ $role->id }}">Deselect All</button>
                                                                </div>
                                                                
                                                                <div class="card card-tabs">
                                                                    <div class="card-header p-0 pt-1 border-bottom-0">
                                                                        <ul class="nav nav-tabs" id="permission-tabs-{{ $role->id }}" role="tablist">
                                                                            @php
                                                                                // Group permissions by their prefix (module)
                                                                                $groupedPermissions = $permissions->groupBy(function($permission) {
                                                                                    $parts = explode('.', $permission->name);
                                                                                    return count($parts) > 1 ? $parts[0] : 'general';
                                                                                });
                                                                                $firstGroup = true;
                                                                            @endphp
                                                                            
                                                                            @foreach($groupedPermissions as $group => $permissions)
                                                                                <li class="nav-item">
                                                                                    <a class="nav-link {{ $firstGroup ? 'active' : '' }}" 
                                                                                       id="{{ $group }}-tab-{{ $role->id }}" 
                                                                                       data-toggle="pill" 
                                                                                       href="#{{ $group }}-permissions-{{ $role->id }}" 
                                                                                       role="tab" 
                                                                                       aria-controls="{{ $group }}-permissions-{{ $role->id }}" 
                                                                                       aria-selected="{{ $firstGroup ? 'true' : 'false' }}">
                                                                                        {{ ucfirst($group) }}
                                                                                        <span class="badge badge-info ml-1">{{ count($permissions) }}</span>
                                                                                    </a>
                                                                                </li>
                                                                                @php $firstGroup = false; @endphp
                                                                            @endforeach
                                                                        </ul>
                                                                    </div>
                                                                    <div class="card-body">
                                                                        <div class="tab-content" id="permission-tabsContent-{{ $role->id }}">
                                                                            @php $firstGroup = true; @endphp
                                                                            @foreach($groupedPermissions as $group => $permissions)
                                                                                <div class="tab-pane fade {{ $firstGroup ? 'show active' : '' }}" 
                                                                                     id="{{ $group }}-permissions-{{ $role->id }}" 
                                                                                     role="tabpanel" 
                                                                                     aria-labelledby="{{ $group }}-tab-{{ $role->id }}">
                                                                                    
                                                                                    <div class="form-group">
                                                                                        <div class="d-flex justify-content-between mb-2">
                                                                                            <h5>{{ ucfirst($group) }} Permissions</h5>
                                                                                            <div>
                                                                                                <button type="button" class="btn btn-xs btn-outline-primary select-group-{{ $role->id }}" data-group="{{ $group }}" data-role="{{ $role->id }}" data-toggle="tooltip" title="Select all permissions in this group">
                                                            <i class="fas fa-check-square mr-1"></i> Select All
                                                        </button>
                                                        <button type="button" class="btn btn-xs btn-outline-secondary deselect-group-{{ $role->id }}" data-group="{{ $group }}" data-role="{{ $role->id }}" data-toggle="tooltip" title="Deselect all permissions in this group">
                                                            <i class="far fa-square mr-1"></i> Deselect All
                                                        </button>
                                                                                            </div>
                                                                                        </div>
                                                                                        
                                                                                        <div class="row">
                                                                                            @foreach($permissions->chunk(ceil($permissions->count() / 3)) as $permissionChunk)
                                                                                                <div class="col-md-4">
                                                                                                    @foreach($permissionChunk as $permission)
                                                                                                        <div class="custom-control custom-checkbox">
                                                                                                            <input type="checkbox" 
                                                                                                                   class="custom-control-input permission-checkbox-{{ $role->id }} {{ $group }}-permission-{{ $role->id }}" 
                                                                                                                   id="permission{{ $role->id }}_{{ $permission->id }}" 
                                                                                                                   name="permissions[]" 
                                                                                                                   value="{{ $permission->id }}" 
                                                                                                                   {{ $role->permissions->contains($permission->id) ? 'checked' : '' }}>
                                                                                                            <label class="custom-control-label" 
                                                                                                                   for="permission{{ $role->id }}_{{ $permission->id }}" 
                                                                                                                   title="{{ $permission->name }}">
                                                                                                                {{ str_replace($group.'.', '', $permission->name) }}
                                                                                                            </label>
                                                                                                        </div>
                                                                                                    @endforeach
                                                                                                </div>
                                                                                            @endforeach
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                                @php $firstGroup = false; @endphp
                                                                            @endforeach
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                                                            <button type="submit" class="btn btn-primary">Update Role</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Delete Role Modal -->
                                        <div class="modal fade" id="deleteRoleModal{{ $role->id }}">
                                            <div class="modal-dialog">
                                                <div class="modal-content">
                                                    <div class="modal-header bg-danger">
                                                        <h4 class="modal-title">Delete Role</h4>
                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                            <span aria-hidden="true">&times;</span>
                                                        </button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <p>Are you sure you want to delete the role "{{ $role->name }}"?</p>
                                                        @if(\App\Models\User::role($role->name)->count() > 0)
                                                            <div class="alert alert-warning">
                                                                <i class="fas fa-exclamation-triangle"></i> This role is assigned to {{ \App\Models\User::role($role->name)->count() }} users. Deleting it will remove these permissions from those users.
                                                            </div>
                                                        @endif
                                                    </div>
                                                    <div class="modal-footer justify-content-between">
                                                        <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fas fa-times mr-1"></i> Cancel</button>
                                                        <form action="{{ route('settings.delete-role', $role->id) }}" method="POST" style="display: inline;">
                                                            @csrf
                                                            @method('DELETE')
                                                            <button type="submit" class="btn btn-danger" data-toggle="tooltip" title="Permanently delete this role"><i class="fas fa-trash mr-1"></i> Delete Role</button>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="4" class="text-center">No roles defined</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <div class="card card-info">
            <div class="card-header">
                <h3 class="card-title">Available Permissions</h3>
            </div>
            <div class="card-body">
                <div class="alert alert-info">
                    <i class="fas fa-info-circle mr-1"></i> These permissions can be assigned to roles. Permissions are grouped by module for easier management.
                </div>
                
                <div class="row">
                    @php
                        // Group permissions by their prefix (module) using dot notation
                        $groupedPermissions = $permissions->groupBy(function($permission) {
                            $parts = explode('.', $permission->name);
                            return count($parts) > 1 ? $parts[0] : 'general';
                        });
                    @endphp
                    
                    @foreach($groupedPermissions as $group => $groupPermissions)
                        <div class="col-md-4 mb-4">
                            <div class="card card-outline card-info">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="fas fa-shield-alt mr-1"></i> {{ ucfirst($group) }}
                                    </h3>
                                    <span class="badge badge-info float-right">{{ count($groupPermissions) }}</span>
                                </div>
                                <div class="card-body p-0">
                                    <ul class="list-group list-group-flush">
                                        @foreach($groupPermissions as $permission)
                                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                                {{ str_replace($group.'.', '', $permission->name) }}
                                                <span class="text-muted small">{{ $permission->name }}</span>
                                            </li>
                                        @endforeach
                                    </ul>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Create Role Modal -->
<div class="modal fade" id="createRoleModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h4 class="modal-title"><i class="fas fa-user-shield mr-2"></i>Create New Police Rank/Role</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form action="{{ route('settings.create-role') }}" method="POST">
                @csrf
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="name">Rank/Role Name</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"><i class="fas fa-id-badge"></i></span>
                                    </div>
                                    <input type="text" class="form-control" id="name" name="name" required placeholder="e.g. Inspector, Sergeant, etc.">
                                </div>
                                <small class="form-text text-muted">Official title of the police rank or role</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="rank_level">Rank Level</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"><i class="fas fa-sort-numeric-up-alt"></i></span>
                                    </div>
                                    <select class="form-control" id="rank_level" name="rank_level" required>
                                        <option value="">Select Rank Level</option>
                                        <option value="1">1 - Junior Officer</option>
                                        <option value="2">2 - Constable</option>
                                        <option value="3">3 - Corporal</option>
                                        <option value="4">4 - Sergeant</option>
                                        <option value="5">5 - Inspector</option>
                                        <option value="6">6 - Chief Inspector</option>
                                        <option value="7">7 - Superintendent</option>
                                        <option value="8">8 - Chief Superintendent</option>
                                        <option value="9">9 - Assistant Commissioner</option>
                                        <option value="10">10 - Commissioner</option>
                                    </select>
                                </div>
                                <small class="form-text text-muted">Determines hierarchy and access level (higher number = more access)</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="description">Description</label>
                                <textarea class="form-control" id="description" name="description" rows="2" placeholder="Brief description of this rank's responsibilities"></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Rank Type</label>
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="is_police_rank" name="is_police_rank" checked>
                                    <label class="custom-control-label" for="is_police_rank">Official Police Rank</label>
                                </div>
                                <small class="form-text text-muted">Toggle off for administrative or civilian roles</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Supervisory Authority</label>
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="can_supervise" name="can_supervise">
                                    <label class="custom-control-label" for="can_supervise">Can supervise others</label>
                                </div>
                                <small class="form-text text-muted">Enables approval and review capabilities</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="jurisdiction_level">Jurisdiction Level</label>
                        <select class="form-control" id="jurisdiction_level" name="jurisdiction_level">
                            <option value="station">Station Level</option>
                            <option value="district">District Level</option>
                            <option value="regional">Regional Level</option>
                            <option value="national">National Level</option>
                        </select>
                        <small class="form-text text-muted">Determines the geographical scope of authority</small>
                    </div>
                    
                    <hr>
                    
                    <div class="form-group">
                        <label><i class="fas fa-key mr-1"></i>Access Permissions</label>
                        <p class="text-muted">Select the permissions to assign to this police rank/role</p>
                        
                        <div class="mb-2">
                            <button type="button" class="btn btn-xs btn-outline-primary select-all-permissions" data-toggle="tooltip" title="Select all permissions">
                                <i class="fas fa-check-square mr-1"></i> Select All
                            </button>
                            <button type="button" class="btn btn-xs btn-outline-secondary deselect-all-permissions" data-toggle="tooltip" title="Deselect all permissions">
                                <i class="far fa-square mr-1"></i> Deselect All
                            </button>
                            <div class="float-right">
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="auto_assign_by_rank" name="auto_assign_by_rank">
                                    <label class="custom-control-label" for="auto_assign_by_rank">Auto-assign based on rank level</label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card card-tabs">
                            <div class="card-header p-0 pt-1 border-bottom-0">
                                <ul class="nav nav-tabs" id="permission-tabs" role="tablist">
                                    @php
                                        // Define police-specific permission categories with icons
                                        $policeCategories = [
                                            'cases' => ['icon' => 'fas fa-folder-open', 'label' => 'Case Management'],
                                            'evidence' => ['icon' => 'fas fa-fingerprint', 'label' => 'Evidence Handling'],
                                            'suspects' => ['icon' => 'fas fa-user-secret', 'label' => 'Suspect Management'],
                                            'victims' => ['icon' => 'fas fa-user-injured', 'label' => 'Victim Services'],
                                            'bail' => ['icon' => 'fas fa-gavel', 'label' => 'Bail Management'],
                                            'reports' => ['icon' => 'fas fa-chart-bar', 'label' => 'Reports & Statistics'],
                                            'settings' => ['icon' => 'fas fa-cogs', 'label' => 'System Settings'],
                                            'users' => ['icon' => 'fas fa-users', 'label' => 'User Management'],
                                            'general' => ['icon' => 'fas fa-shield-alt', 'label' => 'General Access']
                                        ];
                                        
                                        // Group permissions by their prefix (module)
                                        $groupedPermissions = $permissions->groupBy(function($permission) {
                                            $parts = explode('.', $permission->name);
                                            return count($parts) > 1 ? $parts[0] : 'general';
                                        });
                                        $firstGroup = true;
                                    @endphp
                                    
                                    @foreach($groupedPermissions as $group => $permissions)
                                        <li class="nav-item">
                                            <a class="nav-link {{ $firstGroup ? 'active' : '' }}" 
                                               id="{{ $group }}-tab" 
                                               data-toggle="pill" 
                                               href="#{{ $group }}-permissions" 
                                               role="tab" 
                                               aria-controls="{{ $group }}-permissions" 
                                               aria-selected="{{ $firstGroup ? 'true' : 'false' }}">
                                                <i class="{{ isset($policeCategories[$group]) ? $policeCategories[$group]['icon'] : 'fas fa-lock' }} mr-1"></i>
                                                {{ isset($policeCategories[$group]) ? $policeCategories[$group]['label'] : ucfirst($group) }}
                                                <span class="badge badge-info ml-1">{{ count($permissions) }}</span>
                                            </a>
                                        </li>
                                        @php $firstGroup = false; @endphp
                                    @endforeach
                                </ul>
                            </div>
                            <div class="card-body">
                                <div class="tab-content" id="permission-tabsContent">
                                    @php $firstGroup = true; @endphp
                                    @foreach($groupedPermissions as $group => $permissions)
                                        <div class="tab-pane fade {{ $firstGroup ? 'show active' : '' }}" 
                                             id="{{ $group }}-permissions" 
                                             role="tabpanel" 
                                             aria-labelledby="{{ $group }}-tab">
                                            
                                            <div class="form-group">
                                                <div class="d-flex justify-content-between mb-2">
                                                    <h5>
                                                        <i class="{{ isset($policeCategories[$group]) ? $policeCategories[$group]['icon'] : 'fas fa-lock' }} mr-1"></i>
                                                        {{ isset($policeCategories[$group]) ? $policeCategories[$group]['label'] : ucfirst($group) }} Permissions
                                                    </h5>
                                                    <div>
                                                        <button type="button" class="btn btn-xs btn-outline-primary select-group" data-group="{{ $group }}" data-toggle="tooltip" title="Select all permissions in this group">
                                                            <i class="fas fa-check-square mr-1"></i> Select All
                                                        </button>
                                                        <button type="button" class="btn btn-xs btn-outline-secondary deselect-group" data-group="{{ $group }}" data-toggle="tooltip" title="Deselect all permissions in this group">
                                                            <i class="far fa-square mr-1"></i> Deselect All
                                                        </button>
                                                    </div>
                                                </div>
                                                @if($group == 'cases' || $group == 'evidence' || $group == 'suspects')
                                                <div class="alert alert-info alert-sm">
                                                    <i class="fas fa-info-circle mr-1"></i>
                                                    <small>These permissions control access to sensitive police operations. Higher rank levels automatically get more access.</small>
                                                </div>
                                                @endif
                                                
                                                <div class="row">
                                                    @foreach($permissions->chunk(ceil($permissions->count() / 3)) as $permissionChunk)
                                                        <div class="col-md-4">
                                                            @foreach($permissionChunk as $permission)
                                                                <div class="custom-control custom-checkbox">
                                                                    @php
                                                                        $permName = str_replace($group.'.', '', $permission->name);
                                                                        $accessType = 'other';
                                                                        if (strpos($permName, 'view') !== false || strpos($permName, 'list') !== false || strpos($permName, 'read') !== false) {
                                                                            $accessType = 'view';
                                                                        } elseif (strpos($permName, 'create') !== false || strpos($permName, 'add') !== false || strpos($permName, 'store') !== false) {
                                                                            $accessType = 'create';
                                                                        } elseif (strpos($permName, 'edit') !== false || strpos($permName, 'update') !== false || strpos($permName, 'modify') !== false) {
                                                                            $accessType = 'edit';
                                                                        } elseif (strpos($permName, 'delete') !== false || strpos($permName, 'remove') !== false || strpos($permName, 'destroy') !== false) {
                                                                            $accessType = 'delete';
                                                                        }
                                                                    @endphp
                                                                    <input type="checkbox" 
                                                                           class="custom-control-input permission-checkbox {{ $group }}-permission" 
                                                                           id="permission_{{ $permission->id }}" 
                                                                           name="permissions[]" 
                                                                           data-access="{{ $accessType }}"
                                                                           value="{{ $permission->id }}">
                                                                    <label class="custom-control-label" for="permission_{{ $permission->id }}" 
                                                                           title="{{ $permission->name }}">
                                                                        {{ str_replace($group.'.', '', $permission->name) }}
                                                                    </label>
                                                                </div>
                                                            @endforeach
                                                        </div>
                                                    @endforeach
                                                </div>
                                            </div>
                                        </div>
                                        @php $firstGroup = false; @endphp
                                    @endforeach
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fas fa-times mr-1"></i> Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save mr-1"></i> Create Role</button>
                </div>
            </form>
        </div>
    </div>
</div>

@stop

@section('css')
    <link rel="stylesheet" href="/css/admin_custom.css">
@stop

@section('js')
<script>
    $(document).ready(function() {
        // Initialize tooltips
        $('[title]').tooltip();
        $('[data-toggle="tooltip"]').tooltip();
        
        // Initialize select2
        $('.select2').select2();
        
        // Create Role Modal
        // Select all permissions
        $('.select-all-permissions').click(function() {
            $('.permission-checkbox').prop('checked', true);
        });
        
        // Auto-assign permissions based on rank level when checkbox is toggled
        $('#auto_assign_by_rank').change(function() {
            if($(this).is(':checked')) {
                var rankLevel = $('#rank_level').val();
                if(rankLevel) {
                    autoAssignPermissionsByRank(rankLevel);
                }
            }
        });
        
        // Update permissions when rank level changes if auto-assign is checked
        $('#rank_level').change(function() {
            if($('#auto_assign_by_rank').is(':checked')) {
                autoAssignPermissionsByRank($(this).val());
            }
        });
        
        // Function to auto-assign permissions based on rank level
        function autoAssignPermissionsByRank(rankLevel) {
            // Reset all permissions
            $('.permission-checkbox').prop('checked', false);
            
            // Convert to integer
            rankLevel = parseInt(rankLevel);
            
            // Basic access for all ranks (levels 1-10)
            if(rankLevel >= 1) {
                $('[id^="permission_"][data-access="view"]').prop('checked', true);
            }
            
            // Standard access (levels 3-10)
            if(rankLevel >= 3) {
                $('.cases-permission[data-access="create"]').prop('checked', true);
                $('.evidence-permission[data-access="create"]').prop('checked', true);
                $('.suspects-permission[data-access="create"]').prop('checked', true);
                $('.victims-permission[data-access="create"]').prop('checked', true);
            }
            
            // Enhanced access (levels 5-10)
            if(rankLevel >= 5) {
                $('.cases-permission[data-access="edit"]').prop('checked', true);
                $('.evidence-permission[data-access="edit"]').prop('checked', true);
                $('.suspects-permission[data-access="edit"]').prop('checked', true);
                $('.victims-permission[data-access="edit"]').prop('checked', true);
                $('.reports-permission[data-access="view"]').prop('checked', true);
            }
            
            // Advanced access (levels 7-10)
            if(rankLevel >= 7) {
                $('.cases-permission[data-access="delete"]').prop('checked', true);
                $('.evidence-permission[data-access="delete"]').prop('checked', true);
                $('.suspects-permission[data-access="delete"]').prop('checked', true);
                $('.victims-permission[data-access="delete"]').prop('checked', true);
                $('.users-permission[data-access="view"]').prop('checked', true);
                $('.users-permission[data-access="create"]').prop('checked', true);
            }
            
            // Complete access (levels 9-10)
            if(rankLevel >= 9) {
                $('.settings-permission').prop('checked', true);
                $('.users-permission').prop('checked', true);
                $('.reports-permission').prop('checked', true);
                // Check all remaining permissions
                $('.permission-checkbox').prop('checked', true);
            }
        }
        
        // Deselect all permissions
        $('.deselect-all-permissions').click(function() {
            $('.permission-checkbox').prop('checked', false);
        });
        
        // Select all permissions in a group
        $('.select-group').click(function() {
            var group = $(this).data('group');
            $('.' + group + '-permission').prop('checked', true);
        });
        
        // Deselect all permissions in a group
        $('.deselect-group').click(function() {
            var group = $(this).data('group');
            $('.' + group + '-permission').prop('checked', false);
        });
        
        // Edit Role Modals
        // For each role's edit modal
        @foreach($roles as $role)
            // Select all permissions for this role
            $('.select-all-permissions-{{ $role->id }}').click(function() {
                $('.permission-checkbox-{{ $role->id }}').prop('checked', true);
            });
            
            // Deselect all permissions for this role
            $('.deselect-all-permissions-{{ $role->id }}').click(function() {
                $('.permission-checkbox-{{ $role->id }}').prop('checked', false);
            });
            
            // Select all permissions in a group for this role
            $('.select-group-{{ $role->id }}').click(function() {
                var group = $(this).data('group');
                $('.' + group + '-permission-{{ $role->id }}').prop('checked', true);
            });
            
            // Deselect all permissions in a group for this role
            $('.deselect-group-{{ $role->id }}').click(function() {
                var group = $(this).data('group');
                $('.' + group + '-permission-{{ $role->id }}').prop('checked', false);
            });
        @endforeach
    });
</script>
@stop

<!-- Police Rank Information Modal -->
<div class="modal fade" id="rankInfoModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-info">
                <h4 class="modal-title"><i class="fas fa-info-circle mr-2"></i>Police Rank Hierarchy & Access System</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="fas fa-shield-alt mr-2"></i>
                    <strong>About the Police Rank System</strong>
                    <p>This system implements a comprehensive role-based access control tailored specifically for police organizations. Each rank has predefined access levels based on jurisdiction and authority.</p>
                </div>
                
                <h5><i class="fas fa-sort-numeric-up-alt mr-1"></i> Rank Levels</h5>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead class="thead-light">
                            <tr>
                                <th>Level</th>
                                <th>Typical Ranks</th>
                                <th>Access Level</th>
                                <th>Typical Responsibilities</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>1-2</td>
                                <td>Junior Officer, Constable</td>
                                <td><span class="badge badge-info">Basic</span></td>
                                <td>Data entry, basic case viewing, limited evidence access</td>
                            </tr>
                            <tr>
                                <td>3-4</td>
                                <td>Corporal, Sergeant</td>
                                <td><span class="badge badge-primary">Standard</span></td>
                                <td>Case management, suspect processing, evidence handling</td>
                            </tr>
                            <tr>
                                <td>5-6</td>
                                <td>Inspector, Chief Inspector</td>
                                <td><span class="badge badge-success">Enhanced</span></td>
                                <td>Case approval, bail decisions, station-level reporting</td>
                            </tr>
                            <tr>
                                <td>7-8</td>
                                <td>Superintendent, Chief Superintendent</td>
                                <td><span class="badge badge-warning">Advanced</span></td>
                                <td>District oversight, resource allocation, sensitive cases</td>
                            </tr>
                            <tr>
                                <td>9-10</td>
                                <td>Assistant Commissioner, Commissioner</td>
                                <td><span class="badge badge-danger">Complete</span></td>
                                <td>System administration, national reporting, all access</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <h5 class="mt-4"><i class="fas fa-map-marked-alt mr-1"></i> Jurisdiction Levels</h5>
                <div class="row">
                    <div class="col-md-6">
                        <ul class="list-group">
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                Station Level
                                <span class="badge badge-primary badge-pill">Local</span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                District Level
                                <span class="badge badge-info badge-pill">Multiple Stations</span>
                            </li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <ul class="list-group">
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                Regional Level
                                <span class="badge badge-warning badge-pill">Multiple Districts</span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                National Level
                                <span class="badge badge-danger badge-pill">All Regions</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fas fa-times mr-1"></i> Close</button>
            </div>
        </div>
    </div>
</div>
