@extends('layouts.app')
@section('title', 'Permission Matrix — ' . $role->name)
@section('header', 'Permission Matrix: ' . $role->name)

@section('content')
<div style="font-size: 12px; color: #8e9ab4; margin-bottom: 12px;">
    <a href="{{ route('roles.index') }}" style="color: #6d59ff; text-decoration: none;">← Back to Roles Directory</a>
</div>

<!-- FLASH NOTIFICATIONS -->
@if(session('success'))
    <div class="ok" style="margin-bottom: 16px;">
        ✓ {{ session('success') }}
    </div>
@endif

<!-- ROLE HEADER BANNER -->
<div class="panel" style="margin-top: 0; margin-bottom: 18px; padding: 18px 22px; background: linear-gradient(135deg, #101a38 0%, #0d152c 100%);">
    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 14px;">
        <div>
            <div style="display: flex; align-items: center; gap: 10px;">
                <h1 style="margin: 0; font-size: 20px; color: #ffffff;">{{ $role->name }}</h1>
                @if($role->is_system)
                    <span class="badge" style="background: #2e1065; color: #d8b4fe; border: 1px solid #581c87;">🔒 System Core Role</span>
                @else
                    <span class="badge" style="background: #142e2b; color: #6ee7b7; border: 1px solid #1a534c;">Custom Role</span>
                @endif
                <span class="badge badge-active">{{ ucfirst($role->status) }}</span>
            </div>
            <p style="color: #8e9ab4; margin: 4px 0 0; font-size: 13px;">
                {{ $role->description ?: 'Configure module capabilities and record access scopes for this role.' }}
            </p>
        </div>

        <div>
            <a href="{{ route('users', ['role' => $role->slug]) }}" class="btn btn-secondary btn-sm" style="font-weight: 600;">
                👥 View Assigned Users ({{ \App\Models\User::where('role', $role->slug)->count() }})
            </a>
        </div>
    </div>
</div>

<!-- PERMISSION MATRIX CONTROLS TOOLBAR -->
<div class="panel" style="margin-top: 0; margin-bottom: 16px; padding: 12px 18px;">
    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px;">
        <!-- Left: Quick Toggles -->
        <div style="display: flex; gap: 8px;">
            <button type="button" class="btn btn-secondary btn-sm" onclick="selectAllPerms(true)">
                ✓ Select All
            </button>
            <button type="button" class="btn btn-secondary btn-sm" onclick="selectAllPerms(false)">
                ✕ Deselect All
            </button>
        </div>

        <!-- Right: Live Search -->
        <div style="min-width: 260px;">
            <input type="text" id="permSearchInput" onkeyup="filterPermissions(this.value)" placeholder="Filter permissions..." style="margin: 0; padding: 6px 12px; font-size: 12px;">
        </div>
    </div>
</div>

<!-- PERMISSION MATRIX FORM -->
<form method="POST" action="{{ route('roles.permissions.update', $role) }}" id="permissionMatrixForm">
    @csrf

    @foreach($modules as $moduleName => $permissions)
        <div class="panel module-permission-panel" style="margin-top: 0; margin-bottom: 16px; padding: 0; overflow: hidden;" data-module="{{ strtolower($moduleName) }}">
            <!-- Module Header Bar -->
            <div style="background: #101b38; padding: 10px 18px; border-bottom: 1px solid #1c2a4f; display: flex; justify-content: space-between; align-items: center;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <label style="display: flex; align-items: center; gap: 8px; margin: 0; cursor: pointer; font-size: 13px; font-weight: 700; color: #818cf8; text-transform: uppercase; letter-spacing: 0.5px;">
                        <input type="checkbox" class="module-master-checkbox" onchange="toggleModuleGroup(this, '{{ Str::slug($moduleName) }}')" style="width: auto; margin: 0;">
                        <span>{{ $moduleName }}</span>
                    </label>
                </div>
                <span style="font-size: 11px; color: #8e9ab4;">{{ count($permissions) }} capabilities</span>
            </div>

            <!-- Permissions Table for this module -->
            <div style="padding: 12px 18px; overflow-x: auto;">
                <table style="width: 100%;">
                    <thead>
                        <tr>
                            <th style="width: 40px; text-align: center;">Allow</th>
                            <th style="width: 240px;">Capability</th>
                            <th>Description</th>
                            <th style="width: 220px;">Access Scope</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($permissions as $p)
                            @php
                                $rolePerm = $rolePermissions->get($p->slug);
                                $isChecked = $rolePerm !== null || $role->slug === 'super-admin' || $role->slug === 'admin';
                                $currentScope = $rolePerm->access_scope ?? 'all';
                            @endphp
                            <tr class="perm-row" data-search-text="{{ strtolower($p->name . ' ' . $p->slug . ' ' . $p->description) }}">
                                <td style="text-align: center;">
                                    <input type="checkbox" 
                                           name="permissions[]" 
                                           value="{{ $p->slug }}" 
                                           class="perm-checkbox group-{{ Str::slug($moduleName) }}"
                                           {{ $isChecked ? 'checked' : '' }}
                                           style="width: auto; margin: 0;">
                                </td>
                                <td>
                                    <strong style="color: #ffffff; font-size: 13px; display: block;">{{ $p->name }}</strong>
                                    <code style="color: #8e9ab4; font-size: 10.5px;">{{ $p->slug }}</code>
                                </td>
                                <td style="color: #94a3b8; font-size: 12px;">
                                    {{ $p->description }}
                                </td>
                                <td>
                                    <select name="scopes[{{ $p->slug }}]" style="margin: 0; padding: 4px 8px; font-size: 11.5px;">
                                        <option value="all" {{ $currentScope === 'all' ? 'selected' : '' }}>All Records (Global)</option>
                                        <option value="own" {{ $currentScope === 'own' ? 'selected' : '' }}>Own Records Only</option>
                                        <option value="team" {{ $currentScope === 'team' ? 'selected' : '' }}>Team Records</option>
                                        <option value="department" {{ $currentScope === 'department' ? 'selected' : '' }}>Department Records</option>
                                        <option value="branch" {{ $currentScope === 'branch' ? 'selected' : '' }}>Branch Records</option>
                                    </select>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    @endforeach

    <!-- STICKY BOTTOM SAVE ACTION BAR -->
    <div class="panel" style="position: sticky; bottom: 12px; margin-top: 18px; padding: 14px 20px; background: #0c1428; border: 1px solid #28375c; border-radius: 10px; display: flex; justify-content: space-between; align-items: center; z-index: 100; box-shadow: 0 10px 25px rgba(0,0,0,0.5);">
        <div>
            <strong style="color: #ffffff; font-size: 13px;">Save Permissions for {{ $role->name }}</strong>
            <p style="color: #8e9ab4; margin: 2px 0 0; font-size: 11.5px;">Changes will apply immediately to all active users with this role.</p>
        </div>
        <div style="display: flex; gap: 10px;">
            <a href="{{ route('roles.index') }}" class="btn btn-secondary" style="text-decoration: none;">Cancel</a>
            <button type="submit" class="btn" style="padding: 8px 18px; font-weight: 700;">
                💾 Save Permission Matrix
            </button>
        </div>
    </div>
</form>

<script>
function selectAllPerms(check) {
    document.querySelectorAll('.perm-checkbox').forEach(cb => cb.checked = check);
    document.querySelectorAll('.module-master-checkbox').forEach(cb => cb.checked = check);
}

function toggleModuleGroup(master, groupSlug) {
    document.querySelectorAll('.group-' + groupSlug).forEach(cb => cb.checked = master.checked);
}

function filterPermissions(query) {
    const q = query.toLowerCase().trim();
    const rows = document.querySelectorAll('.perm-row');
    const panels = document.querySelectorAll('.module-permission-panel');

    rows.forEach(row => {
        const text = row.getAttribute('data-search-text') || '';
        if (!q || text.includes(q)) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });

    panels.forEach(panel => {
        const visibleRows = panel.querySelectorAll('.perm-row:not([style*="display: none"])');
        panel.style.display = (visibleRows.length > 0) ? '' : 'none';
    });
}
</script>
@endsection
