@extends('layouts.admin')

@section('title', 'Rol Yönetimi')
@section('page-title', 'Rol Yönetimi')
@section('page-subtitle', 'Sistem rolleri ve izinleri')

@section('content')
<div class="mt-4">
    <div class="flex justify-end mb-4">
        <a href="{{ route('admin.roller.create') }}"
           class="bg-primary text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-orange-600 transition-colors flex items-center gap-1.5">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
            Yeni Rol
        </a>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <table class="w-full text-sm">
            <thead class="bg-gray-50 border-b border-gray-100">
                <tr>
                    <th class="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Rol Adı</th>
                    <th class="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">İzinler</th>
                    <th class="text-center px-5 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Kullanıcı</th>
                    <th class="px-5 py-3"></th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-50">
                @foreach($roles as $role)
                <tr class="hover:bg-gray-50 transition-colors role-row"
                    data-name="{{ $role->name }}"
                    data-edit-url="{{ route('admin.roller.edit', $role) }}"
                    data-delete-url="{{ route('admin.roller.destroy', $role) }}"
                    data-is-system="{{ $role->name === 'super-admin' ? '1' : '0' }}"
                    data-user-count="{{ $role->users_count }}">
                    <td class="px-5 py-4">
                        <div class="flex items-center gap-2">
                            <span class="font-semibold text-gray-800">{{ $role->name }}</span>
                            @if($role->name === 'super-admin')
                            <span class="text-xs bg-orange-100 text-orange-700 px-2 py-0.5 rounded-full font-medium">Sistem</span>
                            @endif
                        </div>
                    </td>
                    <td class="px-5 py-4">
                        <div class="flex flex-wrap gap-1">
                            @forelse($role->permissions->take(5) as $perm)
                            <span class="text-xs bg-blue-50 text-blue-700 px-2 py-0.5 rounded-full">{{ $perm->name }}</span>
                            @empty
                            <span class="text-xs text-gray-400">İzin yok</span>
                            @endforelse
                            @if($role->permissions->count() > 5)
                            <span class="text-xs bg-gray-100 text-gray-500 px-2 py-0.5 rounded-full">+{{ $role->permissions->count() - 5 }} daha</span>
                            @endif
                        </div>
                    </td>
                    <td class="px-5 py-4 text-center">
                        <span class="font-medium text-gray-700">{{ $role->users_count }}</span>
                    </td>
                    <td class="px-5 py-4 text-right">
                        <div class="flex items-center justify-end gap-2">
                            <a href="{{ route('admin.roller.edit', $role) }}"
                               class="text-xs border border-gray-300 text-gray-600 px-3 py-1.5 rounded-lg hover:bg-gray-50 transition-colors">
                                Düzenle
                            </a>
                            @if($role->name !== 'super-admin' && $role->users_count === 0)
                            <form method="POST" action="{{ route('admin.roller.destroy', $role) }}"
                                  class="role-delete-form">
                                @csrf
                                @method('DELETE')
                                <input type="hidden" name="_role_name" value="{{ $role->name }}">
                                <button type="submit"
                                        class="text-xs border border-red-200 text-red-500 px-3 py-1.5 rounded-lg hover:bg-red-50 transition-colors">
                                    Sil
                                </button>
                            </form>
                            @endif
                        </div>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</div>

{{-- Sağ Tık Menüsü --}}
<div id="roleContextMenu" style="position:fixed;z-index:9999;background:white;border:1px solid #e5e7eb;border-radius:12px;box-shadow:0 12px 36px rgba(0,0,0,.14);min-width:180px;padding:4px 0;display:none;">
    <a id="ctxRoleEdit" href="#" class="ctx-role-item" style="display:flex;align-items:center;gap:9px;padding:9px 14px;font-size:.8rem;color:#374151;text-decoration:none;">
        <svg style="width:14px;height:14px;flex-shrink:0;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
        Düzenle
    </a>
    <div style="height:1px;background:#f3f4f6;margin:3px 0;" id="ctxRoleDivider"></div>
    <button id="ctxRoleDelete" class="ctx-role-item" style="display:flex;align-items:center;gap:9px;width:100%;padding:9px 14px;font-size:.8rem;color:#dc2626;background:none;border:none;cursor:pointer;text-align:left;">
        <svg style="width:14px;height:14px;flex-shrink:0;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
        Sil
    </button>
</div>

{{-- Gizli delete formu --}}
<form id="ctxRoleDeleteForm" method="POST" style="display:none;">
    @csrf
    @method('DELETE')
</form>

<style>
.ctx-role-item:hover { background: #f9fafb !important; }
</style>

<script nonce="{{ app('csp-nonce') }}">
(function() {
    var menu       = document.getElementById('roleContextMenu');
    if (!menu) return;

    var deleteForm = document.getElementById('ctxRoleDeleteForm');
    var editLink   = document.getElementById('ctxRoleEdit');
    var deleteBtn  = document.getElementById('ctxRoleDelete');
    var divider    = document.getElementById('ctxRoleDivider');

    document.querySelectorAll('.role-row').forEach(function(row) {
        row.addEventListener('contextmenu', function(e) {
            e.preventDefault();

            var isSystem   = row.dataset.isSystem === '1';
            var userCount  = parseInt(row.dataset.userCount) || 0;
            var canDelete  = !isSystem && userCount === 0;

            if (editLink) editLink.href = row.dataset.editUrl;
            if (deleteForm) deleteForm.action = row.dataset.deleteUrl;

            // Sil butonunu ve ayırıcıyı göster/gizle
            if (deleteBtn) {
                if (canDelete) {
                    deleteBtn.style.display = 'flex';
                    if (divider) divider.style.display = 'block';
                } else {
                    deleteBtn.style.display = 'none';
                    if (divider) divider.style.display = 'none';
                }
            }

            var menuW = 190, menuH = canDelete ? 120 : 60;
            var x = e.clientX, y = e.clientY;
            if (x + menuW > window.innerWidth)  x = x - menuW;
            if (y + menuH > window.innerHeight) y = y - menuH;
            menu.style.left    = x + 'px';
            menu.style.top     = y + 'px';
            menu.style.display = 'block';
        });
    });

    if (deleteBtn) {
        deleteBtn.addEventListener('click', function() {
            menu.style.display = 'none';
            if (confirm('Bu rolü kalıcı olarak silmek istediğinizden emin misiniz?\n\nBu işlem GERİ ALINAMAZ!')) {
                deleteForm.submit();
            }
        });
    }

    document.addEventListener('click', function(e) {
        if (menu && !menu.contains(e.target)) menu.style.display = 'none';
    });
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && menu) menu.style.display = 'none';
    });

    // Tablo içindeki silme formları — onsubmit inline handler yerine addEventListener
    document.querySelectorAll('.role-delete-form').forEach(function(form) {
        form.addEventListener('submit', function(e) {
            var roleName = form.querySelector('input[name="_role_name"]');
            var name = roleName ? roleName.value : 'bu rol';
            if (!confirm('"' + name + '" rolünü silmek istediğinizden emin misiniz?')) {
                e.preventDefault();
            }
        });
    });
})();
</script>

@endsection