@extends('admin-layouts.master')

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

@section('content')
<style>
:root {
    --primary-color: #4e73df;
    --success-color: #1cc88a;
    --info-color: #36b9cc;
    --warning-color: #f6c23e;
    --danger-color: #e74a3b;
    --light-bg: #f8f9fc;
    --border-color: #e3e6f0;
}

.card {
    border-radius: 10px;
    border: none;
    box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
    transition: all 0.3s ease;
}

.table th {
    font-size: 0.85rem;
    letter-spacing: 0.5px;
    text-transform: uppercase;
    font-weight: 600;
    color: #5a5c69;
}

.btn-group .btn {
    border-radius: 6px !important;
    margin: 0 2px;
    transition: all 0.3s ease;
}

.btn-group .btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.role-icon {
    flex-shrink: 0;
}

.badge {
    font-size: 0.75rem;
    font-weight: 500;
    padding: 0.35rem 0.65rem;
    border-radius: 6px;
}

.alert {
    border-radius: 8px;
    border: none;
}

.modal-content {
    border-radius: 10px;
    border: none;
}

.modal-backdrop {
    background-color: rgba(0, 0, 0, 0.5);
}

.table-hover tbody tr {
    transition: background-color 0.2s ease;
}

.table-hover tbody tr:hover {
    background-color: #f8f9fa;
}

.pagination .page-link {
    border-radius: 6px;
    margin: 0 2px;
    border: 1px solid var(--border-color);
    color: var(--primary-color);
    transition: all 0.3s ease;
}

.pagination .page-link:hover {
    background-color: var(--light-bg);
    transform: translateY(-2px);
}

.pagination .page-item.active .page-link {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
    box-shadow: 0 2px 8px rgba(78, 115, 223, 0.3);
}

.btn {
    transition: all 0.3s ease;
}

.btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
</style>

<div class="container-fluid">
    <!-- Header Section -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2 class="mb-1 text-dark font-weight-bold">Role Management</h2>
                    <p class="text-muted mb-0">Manage system roles and permissions</p>
                </div>
                @can('role.create')
                <div>
                    <a href="{{ route('roles.create') }}" class="btn btn-primary btn-sm shadow-sm">
                        <i class="fas fa-plus mr-1"></i> Add New Role
                    </a>
                </div>
                @endcan
            </div>
        </div>
    </div>

    <!-- Alert Messages -->
    @if(session('success'))
    <div class="row mb-3">
        <div class="col-md-12">
            <div class="alert alert-success alert-dismissible fade show shadow-sm" role="alert">
                <i class="fas fa-check-circle mr-2"></i>
                {{ session('success') }}
                <button type="button" class="close" data-dismiss="alert">
                    <span>&times;</span>
                </button>
            </div>
        </div>
    </div>
    @endif

    @if(session('error'))
    <div class="row mb-3">
        <div class="col-md-12">
            <div class="alert alert-danger alert-dismissible fade show shadow-sm" role="alert">
                <i class="fas fa-exclamation-circle mr-2"></i>
                {{ session('error') }}
                <button type="button" class="close" data-dismiss="alert">
                    <span>&times;</span>
                </button>
            </div>
        </div>
    </div>
    @endif

    <!-- Main Content Card -->
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header bg-white py-3">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <h6 class="mb-0 text-dark font-weight-bold">
                                <i class="fas fa-users-cog text-primary mr-2"></i>
                                System Roles
                            </h6>
                        </div>
                        <div class="col-md-6 text-right">
                            <span class="badge badge-light px-3 py-2">
                                {{ $roles->total() }} Total Roles
                            </span>
                        </div>
                    </div>
                </div>

                <div class="card-body p-0">
                    @if($roles->count() > 0)
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="bg-light">
                                <tr>
                                    <th class="border-0 py-3 px-4">Role</th>
                                    <th class="border-0 py-3">Permissions</th>
                                    <th class="border-0 py-3">Users</th>
                                    <th class="border-0 py-3">Status</th>
                                    <th class="border-0 py-3 text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($roles as $role)
                                <tr class="border-bottom">
                                    <td class="px-4 py-3">
                                        <div class="d-flex align-items-center">
                                            <div class="role-icon mr-3">
                                                @if($role->name === 'superadmin')
                                                    <div class="bg-danger rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                        <i class="fas fa-crown text-white"></i>
                                                    </div>
                                                @elseif($role->name === 'supervisor')
                                                    <div class="bg-warning rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                        <i class="fas fa-user-tie text-white"></i>
                                                    </div>
                                                @elseif($role->name === 'staff')
                                                    <div class="bg-info rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                        <i class="fas fa-user-edit text-white"></i>
                                                    </div>
                                                @elseif($role->name === 'administrator')
                                                    <div class="bg-success rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                        <i class="fas fa-user-cog text-white"></i>
                                                    </div>
                                                @else
                                                    <div class="bg-secondary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                        <i class="fas fa-user text-white"></i>
                                                    </div>
                                                @endif
                                            </div>
                                            <div>
                                                <h6 class="mb-1 font-weight-semibold text-dark">{{ $role->name }}</h6>
                                                @if($role->description)
                                                <p class="mb-0 text-muted small">{{ Str::limit($role->description, 50) }}</p>
                                                @endif
                                            </div>
                                        </div>
                                    </td>
                                    <td class="py-3">
                                        <span class="badge badge-primary px-3 py-2">
                                            {{ $role->permissions->count() }} permissions
                                        </span>
                                    </td>
                                    <td class="py-3">
                                        <span class="badge badge-light px-3 py-2">
                                            {{ $role->users->count() }} users
                                        </span>
                                    </td>
                                    <td class="py-3">
                                        @if($role->is_active ?? true)
                                            <span class="badge badge-success px-3 py-2">
                                                <i class="fas fa-check mr-1"></i> Active
                                            </span>
                                        @else
                                            <span class="badge badge-secondary px-3 py-2">
                                                <i class="fas fa-times mr-1"></i> Inactive
                                            </span>
                                        @endif
                                    </td>
                                    <td class="py-3 text-center">
                                        <div class="btn-group" role="group">
                                            @can('role.view')
                                            <a href="{{ route('roles.show', $role) }}"
                                               class="btn btn-sm btn-outline-info"
                                               data-toggle="tooltip"
                                               data-placement="top"
                                               title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            @endcan

                                            @can('role.edit')
                                            <a href="{{ route('roles.edit', $role) }}"
                                               class="btn btn-sm btn-outline-warning"
                                               data-toggle="tooltip"
                                               data-placement="top"
                                               title="Edit Role">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            @endcan

                                            @can('role.delete')
                                            @if($role->name !== 'superadmin')
                                            <button type="button"
                                                    class="btn btn-sm btn-outline-danger btn-delete-role"
                                                    data-role-id="{{ $role->id }}"
                                                    data-role-name="{{ $role->name }}"
                                                    data-user-count="{{ $role->users->count() }}"
                                                    data-toggle="tooltip"
                                                    data-placement="top"
                                                    title="Delete Role">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            @endif
                                            @endcan
                                        </div>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    @if($roles->hasPages())
                    <div class="card-footer bg-white py-3">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="text-muted small">
                                Showing {{ $roles->firstItem() }} to {{ $roles->lastItem() }} of {{ $roles->total() }} results
                            </div>
                            {{ $roles->links() }}
                        </div>
                    </div>
                    @endif

                    @else
                    <!-- Empty State -->
                    <div class="text-center py-5">
                        <i class="fas fa-users-cog fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted mb-2">No Roles Found</h5>
                        <p class="text-muted mb-3">There are no roles configured in the system.</p>
                        @can('role.create')
                        <a href="{{ route('roles.create') }}" class="btn btn-primary">
                            <i class="fas fa-plus mr-1"></i> Create First Role
                        </a>
                        @endcan
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Single Delete Modal (Outside Loop) -->
<div class="modal fade" id="deleteRoleModal" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-bottom-0 bg-danger text-white">
                <h6 class="modal-title">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    Confirm Delete
                </h6>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body text-center py-4">
                <i class="fas fa-trash fa-3x text-danger mb-3"></i>
                <h5 class="mb-2">Delete Role "<span id="deleteRoleName"></span>"?</h5>
                <p class="text-muted mb-0">This action cannot be undone. All permissions associated with this role will be removed.</p>
                <div id="userWarning" class="alert alert-warning mt-3" style="display: none;">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    <span id="userWarningText"></span>
                </div>
            </div>
            <div class="modal-footer border-top-0 d-flex justify-content-center">
                <button type="button" class="btn btn-light px-4" data-dismiss="modal">Cancel</button>
                <form id="deleteRoleForm" method="POST" class="ml-2">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-danger px-4" id="confirmDeleteBtn">
                        <i class="fas fa-trash mr-1"></i> Delete
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
$(document).ready(function() {
    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Handle delete button click
    $('.btn-delete-role').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();

        const roleId = $(this).data('role-id');
        const roleName = $(this).data('role-name');
        const userCount = $(this).data('user-count');

        // Update modal content
        $('#deleteRoleName').text(roleName);

        // Update form action
        const deleteUrl = "{{ route('roles.destroy', ':id') }}".replace(':id', roleId);
        $('#deleteRoleForm').attr('action', deleteUrl);

        // Show/hide user warning
        if (userCount > 0) {
            $('#userWarningText').text(`This role is assigned to ${userCount} user(s). You need to reassign them first.`);
            $('#userWarning').show();
            $('#confirmDeleteBtn').prop('disabled', true).addClass('disabled');
        } else {
            $('#userWarning').hide();
            $('#confirmDeleteBtn').prop('disabled', false).removeClass('disabled');
        }

        // Show modal
        $('#deleteRoleModal').modal('show');
    });

    // Clean up when modal is hidden
    $('#deleteRoleModal').on('hidden.bs.modal', function () {
        $(this).find('form').trigger('reset');
        $('#deleteRoleName').text('');
        $('#userWarning').hide();
        $('#confirmDeleteBtn').prop('disabled', false).removeClass('disabled');
    });

    // Auto hide alerts after 5 seconds
    setTimeout(function() {
        $('.alert').not('.alert-warning').fadeOut('slow');
    }, 5000);

    // Prevent multiple modal instances
    $(document).on('show.bs.modal', '.modal', function () {
        const zIndex = 1040 + (10 * $('.modal:visible').length);
        $(this).css('z-index', zIndex);
        setTimeout(function() {
            $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
        }, 0);
    });

    // Remove tooltip on button click to prevent stuck tooltips
    $('[data-toggle="tooltip"]').on('click', function() {
        $(this).tooltip('hide');
    });
});
</script>
@endpush
@endsection
