@extends('layouts.admin-simple')

@section('title', 'Role Management')
@section('page-title', 'Role Management')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item active" aria-current="page">Roles</li>
@endsection

@section('page-actions')
    <div class="ml-auto">
        <a href="{{ route('admin.permissions') }}" class="btn btn-outline-primary mr-2">
            <i class="material-icons">lock</i> Manage Permissions
        </a>
        <a href="{{ route('admin.roles.create') }}" class="btn btn-primary">
            <i class="material-icons">add</i> Create Role
        </a>
    </div>
@endsection

@section('content')
    <div class="card">
        <div class="card-header card-header-large bg-white">
            <h4 class="card-header__title">System Roles</h4>
            <div class="card-subtitle text-muted">Manage user roles and their permissions</div>
        </div>
        
        <div class="table-responsive">
            <table class="table mb-0">
                <thead>
                    <tr>
                        <th>Role Name</th>
                        <th>Description</th>
                        <th>Permissions</th>
                        <th>Users</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($roles as $role)
                    <tr>
                        <td>
                            <div>
                                <strong>{{ $role->display_name }}</strong>
                                <div class="text-muted small">{{ $role->name }}</div>
                            </div>
                        </td>
                        <td>{{ $role->description ?? 'N/A' }}</td>
                        <td>
                            @if($role->permissions->count() > 0)
                                <span class="badge badge-soft-info">{{ $role->permissions->count() }} permissions</span>
                            @else
                                <span class="badge badge-soft-warning">No permissions</span>
                            @endif
                        </td>
                        <td>
                            <span class="badge badge-light">{{ $role->users_count }} users</span>
                        </td>
                        <td>
                            @if($role->is_active)
                                <span class="badge badge-soft-success">Active</span>
                            @else
                                <span class="badge badge-soft-danger">Inactive</span>
                            @endif
                            @if(in_array($role->name, ['super_admin', 'admin', 'hr_manager', 'viewer']))
                                <span class="badge badge-soft-info">System</span>
                            @endif
                        </td>
                        <td>
                            <div class="dropdown">
                                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" id="actionsDropdown{{ $role->id }}" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <i class="material-icons" style="font-size: 16px;">more_vert</i>
                                </button>
                                <div class="dropdown-menu dropdown-menu-right" aria-labelledby="actionsDropdown{{ $role->id }}">
                                    <!-- View Role Details -->
                                    <a class="dropdown-item" href="javascript:void(0)" onclick="viewRoleDetails({{ $role->id }})">
                                        <i class="material-icons mr-2" style="font-size: 16px;">visibility</i>
                                        View Details
                                    </a>

                                    <!-- View Permissions -->
                                    <a class="dropdown-item" href="javascript:void(0)" onclick="viewRolePermissions({{ $role->id }})">
                                        <i class="material-icons mr-2" style="font-size: 16px;">security</i>
                                        View Permissions
                                    </a>

                                    @if($role->name !== 'super_admin')
                                        <div class="dropdown-divider"></div>
                                        <h6 class="dropdown-header">Manage Role</h6>

                                        <!-- Edit Role -->
                                        <a href="{{ route('admin.roles.edit', $role) }}" class="dropdown-item">
                                            <i class="material-icons mr-2" style="font-size: 16px;">edit</i>
                                            Edit Role
                                        </a>

                                        <!-- Duplicate Role -->
                                        <a class="dropdown-item" href="javascript:void(0)" onclick="duplicateRole({{ $role->id }})">
                                            <i class="material-icons mr-2" style="font-size: 16px;">content_copy</i>
                                            Duplicate Role
                                        </a>

                                        <!-- Toggle Status -->
                                        <a class="dropdown-item" href="javascript:void(0)" onclick="toggleRoleStatus({{ $role->id }}, '{{ $role->is_active ? 'deactivate' : 'activate' }}')">
                                            <i class="material-icons mr-2" style="font-size: 16px;">{{ $role->is_active ? 'toggle_off' : 'toggle_on' }}</i>
                                            {{ $role->is_active ? 'Deactivate' : 'Activate' }}
                                        </a>
                                    @endif

                                    @if(!in_array($role->name, ['super_admin', 'admin', 'hr_manager', 'viewer']))
                                        @if($role->users_count == 0)
                                            <div class="dropdown-divider"></div>
                                            <a href="javascript:void(0)" class="dropdown-item text-danger"
                                               onclick="deleteRole({{ $role->id }}, '{{ $role->display_name }}')">
                                                <i class="material-icons mr-2" style="font-size: 16px;">delete</i>
                                                Delete Role
                                            </a>
                                        @else
                                            <div class="dropdown-divider"></div>
                                            <span class="dropdown-item-text text-muted">
                                                <i class="material-icons mr-2" style="font-size: 16px;">lock</i>
                                                Cannot delete ({{ $role->users_count }} users assigned)
                                            </span>
                                        @endif
                                    @endif

                                    <!-- Show message for system roles -->
                                    @if(in_array($role->name, ['super_admin', 'admin', 'hr_manager', 'viewer']) && $role->name !== 'super_admin')
                                        <div class="dropdown-divider"></div>
                                        <span class="dropdown-item-text text-info">
                                            <i class="material-icons mr-2" style="font-size: 16px;">info</i>
                                            System role - Limited actions
                                        </span>
                                    @endif
                                </div>
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="6" class="text-center py-4">
                            <div class="empty-state">
                                <i class="material-icons mb-3" style="font-size: 48px; color: #ddd;">security</i>
                                <h5 class="text-muted">No roles found</h5>
                                <p class="text-muted">Start by creating your first role.</p>
                                <a href="{{ route('admin.roles.create') }}" class="btn btn-primary">
                                    <i class="material-icons">add</i> Create First Role
                                </a>
                            </div>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
@endsection

@push('scripts')
<script>
// Set the base URL for admin routes
window.adminRolesEditUrl = '{{ route("admin.roles.edit", ":roleId") }}';

function deleteRole(roleId, roleName) {
    if (confirm(`Are you sure you want to delete the role "${roleName}"? This action cannot be undone.`)) {
        fetch(`/admin/roles/${roleId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToastMessage(data.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToastMessage(data.message || 'Failed to delete role', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToastMessage('An error occurred while deleting the role', 'error');
        });
    }
}

function viewRoleDetails(roleId) {
    // Find role data from the page data
    const roleRow = document.querySelector(`#actionsDropdown${roleId}`).closest('tr');
    const roleName = roleRow.querySelector('td:first-child strong').textContent;
    const roleSystemName = roleRow.querySelector('td:first-child .text-muted').textContent;
    const roleDescription = roleRow.querySelector('td:nth-child(2)').textContent;
    const permissionsText = roleRow.querySelector('td:nth-child(3) .badge').textContent;
    const usersCount = roleRow.querySelector('td:nth-child(4) .badge').textContent;
    const statusBadge = roleRow.querySelector('td:nth-child(5) .badge-soft-success, td:nth-child(5) .badge-soft-danger');
    const isActive = statusBadge && statusBadge.classList.contains('badge-soft-success');
    const isSystemRole = roleRow.querySelector('td:nth-child(5) .badge-soft-info') !== null;

    // Create role object from page data
    const role = {
        id: roleId,
        display_name: roleName,
        name: roleSystemName,
        description: roleDescription === 'N/A' ? null : roleDescription,
        is_active: isActive,
        users_count: parseInt(usersCount.replace(/\D/g, '')) || 0,
        permissions_count: parseInt(permissionsText.replace(/\D/g, '')) || 0
    };

    // Show modal immediately with available data
    showRoleDetailsModal(role);
}

function showRoleDetailsModal(role) {
    const modalHtml = `
        <div class="modal fade" id="roleDetailsModal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="material-icons mr-2">info</i>
                            Role Details: ${role.display_name}
                        </h5>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6>Basic Information</h6>
                                <table class="table table-sm">
                                    <tr><td><strong>Display Name:</strong></td><td>${role.display_name}</td></tr>
                                    <tr><td><strong>System Name:</strong></td><td><code>${role.name}</code></td></tr>
                                    <tr><td><strong>Status:</strong></td><td><span class="badge badge-${role.is_active ? 'success' : 'danger'}">${role.is_active ? 'Active' : 'Inactive'}</span></td></tr>
                                    <tr><td><strong>Users Assigned:</strong></td><td>${role.users_count || 0}</td></tr>
                                    <tr><td><strong>Total Permissions:</strong></td><td>${role.permissions_count || 0}</td></tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <h6>Description</h6>
                                <p>${role.description || 'No description provided'}</p>

                                <h6>Role Type</h6>
                                <p>
                                    ${['super_admin', 'admin', 'hr_manager', 'viewer'].includes(role.name)
                                        ? '<span class="badge badge-info">System Role</span>'
                                        : '<span class="badge badge-secondary">Custom Role</span>'}
                                </p>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        ${role.name !== 'super_admin' ? `
                        <a href="${window.adminRolesEditUrl.replace(':roleId', role.id)}" class="btn btn-primary">
                            <i class="material-icons mr-1" style="font-size: 16px;">edit</i>
                            Edit Role
                        </a>` : ''}
                    </div>
                </div>
            </div>
        </div>
    `;

    $('#roleDetailsModal').remove();
    $('body').append(modalHtml);
    $('#roleDetailsModal').modal('show');
}

function viewRolePermissions(roleId) {
    // Get role data from page
    const roleRow = document.querySelector(`#actionsDropdown${roleId}`).closest('tr');
    const roleName = roleRow.querySelector('td:first-child strong').textContent;
    const permissionsText = roleRow.querySelector('td:nth-child(3) .badge').textContent;
    const permissionsCount = parseInt(permissionsText.replace(/\D/g, '')) || 0;

    const modalHtml = `
        <div class="modal fade" id="rolePermissionsModal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="material-icons mr-2">security</i>
                            Permissions for: ${roleName}
                        </h5>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="text-center py-4">
                            <i class="material-icons text-primary mb-3" style="font-size: 48px;">security</i>
                            <h6>Role Permissions</h6>
                            <p class="text-muted">This role has <strong>${permissionsCount} permissions</strong> assigned.</p>
                            <div class="alert alert-info">
                                <strong>Note:</strong> For detailed permission management and viewing, please use the edit role page where you can see and modify all individual permissions.
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <a href="${window.adminRolesEditUrl.replace(':roleId', roleId)}" class="btn btn-primary">
                            <i class="material-icons mr-1" style="font-size: 16px;">edit</i>
                            Manage Permissions
                        </a>
                    </div>
                </div>
            </div>
        </div>
    `;

    $('#rolePermissionsModal').remove();
    $('body').append(modalHtml);
    $('#rolePermissionsModal').modal('show');
}

function duplicateRole(roleId) {
    if (confirm('Create a copy of this role? You will be redirected to edit the new role.')) {
        fetch(`/admin/roles/${roleId}/duplicate`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToastMessage('Role duplicated successfully!', 'success');
                setTimeout(() => window.location.href = `/admin/roles/${data.new_role_id}/edit`, 1000);
            } else {
                showToastMessage(data.message || 'Failed to duplicate role', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToastMessage('Error duplicating role', 'error');
        });
    }
}

function toggleRoleStatus(roleId, action) {
    const confirmMessage = action === 'activate'
        ? 'Are you sure you want to activate this role?'
        : 'Are you sure you want to deactivate this role? Users with this role may lose access.';

    if (confirm(confirmMessage)) {
        fetch(`/admin/roles/${roleId}/toggle-status`, {
            method: 'PATCH',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToastMessage(data.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToastMessage(data.message || 'Failed to toggle role status', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToastMessage('Error toggling role status', 'error');
        });
    }
}

// Fallback toast function if not available globally
function showToastMessage(message, type) {
    if (typeof showToast === 'function') {
        showToast(message, type);
    } else {
        // Simple alert fallback
        alert(message);
    }
}
</script>
@endpush