@extends('layouts.admin')

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

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

@section('breadcrumbs')
    <a href="{{ route('admin.settings.index') }}" class="hover:text-primary">Settings</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">Users</span>
@endsection

@section('content')
<div class="max-w-7xl mx-auto">
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between mb-6">
            <div>
                <h2 class="text-xl font-bold text-gray-900">Users Management</h2>
                <p class="text-sm text-gray-500 mt-1">Manage system users and their access</p>
            </div>
            <a href="{{ route('admin.settings.users.create') }}" class="inline-flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                <span class="material-symbols-outlined text-sm">add</span>
                Add New User
            </a>
        </div>

        <!-- Filters -->
        <div class="mb-6 flex flex-col sm:flex-row gap-4">
            <div class="relative flex-1">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <span class="material-symbols-outlined text-gray-400 text-sm">search</span>
                </div>
                <input id="user-search" type="text" placeholder="Search by name or email..." class="block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-lg bg-white text-gray-900 shadow-sm placeholder:text-gray-400 focus:ring-2 focus:ring-primary/20 focus:border-primary sm:text-sm" onkeyup="searchUsers()">
            </div>
            <select id="user-role-filter" class="px-3 py-2.5 border border-gray-300 rounded-lg bg-white text-gray-900 focus:ring-2 focus:ring-primary/20 focus:border-primary sm:text-sm" onchange="searchUsers()">
                <option value="">All Roles</option>
                @foreach($roles ?? [] as $role)
                    <option value="{{ $role->slug }}">{{ $role->name }}</option>
                @endforeach
            </select>
            <select id="user-per-page" class="px-3 py-2.5 border border-gray-300 rounded-lg bg-white text-gray-900 focus:ring-2 focus:ring-primary/20 focus:border-primary sm:text-sm" onchange="searchUsers()">
                <option value="15" {{ request('per_page', 15) == 15 ? 'selected' : '' }}>15 / page</option>
                <option value="25" {{ request('per_page', 15) == 25 ? 'selected' : '' }}>25 / page</option>
                <option value="50" {{ request('per_page', 15) == 50 ? 'selected' : '' }}>50 / page</option>
                <option value="100" {{ request('per_page', 15) == 100 ? 'selected' : '' }}>100 / page</option>
            </select>
        </div>

        <!-- Table -->
        <div class="overflow-x-auto">
            <table class="w-full text-left">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-xs font-semibold text-gray-600 uppercase">User</th>
                        <th class="px-6 py-3 text-xs font-semibold text-gray-600 uppercase">Email</th>
                        <th class="px-6 py-3 text-xs font-semibold text-gray-600 uppercase">Role</th>
                        <th class="px-6 py-3 text-xs font-semibold text-gray-600 uppercase">Status</th>
                        <th class="px-6 py-3 text-xs font-semibold text-gray-600 uppercase text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200" id="users-table-body">
                    @include('admin.settings.partials.users-table-rows', ['users' => $users, 'startIndex' => 0])
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <div class="mt-6 flex items-center justify-between" id="users-pagination">
        @if($users->hasPages())
                <div class="flex-1 flex justify-between sm:hidden">
                    @if($users->onFirstPage())
                        <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white cursor-default">Previous</span>
                    @else
                        <a href="{{ $users->previousPageUrl() }}" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">Previous</a>
                    @endif
                    @if($users->hasMorePages())
                        <a href="{{ $users->nextPageUrl() }}" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">Next</a>
                    @else
                        <span class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white cursor-default">Next</span>
                    @endif
                </div>
                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                        <p class="text-sm text-gray-700">
                            Showing <span class="font-medium" id="users-from">{{ ($users->currentPage() - 1) * $users->perPage() + 1 }}</span> to <span class="font-medium" id="users-to">{{ min($users->currentPage() * $users->perPage(), $users->total()) }}</span> of <span class="font-medium" id="users-total">{{ $users->total() }}</span> results
                        </p>
                    </div>
                    <div>
                        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                            @if($users->onFirstPage())
                                <span class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 cursor-default">Previous</span>
                            @else
                                <a href="{{ $users->previousPageUrl() }}" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">Previous</a>
                            @endif
                            @foreach($users->getUrlRange(1, min(5, $users->lastPage())) as $page => $url)
                                @if($page == $users->currentPage())
                                    <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-primary text-sm font-medium text-white">{{ $page }}</span>
                                @else
                                    <a href="{{ $url }}" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">{{ $page }}</a>
                                @endif
                            @endforeach
                            @if($users->hasMorePages())
                                <a href="{{ $users->nextPageUrl() }}" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">Next</a>
                            @else
                                <span class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 cursor-default">Next</span>
                            @endif
                        </nav>
                    </div>
                </div>
            @else
                <div class="text-sm text-gray-700">
                    Showing <span class="font-medium">{{ $users->count() }}</span> of <span class="font-medium">{{ $users->total() }}</span> results
                </div>
            @endif
        </div>
    </div>
</div>

<!-- Edit User Modal -->
<div id="edit-user-modal" data-admin-modal class="hidden fixed inset-0 z-[100] overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" onclick="document.getElementById('edit-user-modal').classList.add('hidden')"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <form id="edit-user-form" method="POST" enctype="multipart/form-data">
                @csrf
                @method('PUT')
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <div class="sm:flex sm:items-start">
                        <div class="mt-3 text-center sm:mt-0 sm:text-left w-full">
                            <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">Edit User</h3>
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Name <span class="text-red-500">*</span></label>
                                    <input type="text" name="name" id="edit-user-name" required class="mt-1 block w-full rounded-md border border-gray-300 bg-white text-gray-900 py-2 px-3 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Email <span class="text-red-500">*</span></label>
                                    <input type="email" name="email" id="edit-user-email" required class="mt-1 block w-full rounded-md border border-gray-300 bg-white text-gray-900 py-2 px-3 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Role <span class="text-red-500">*</span></label>
                                    <select name="role_id" id="edit-user-role" required class="mt-1 block w-full rounded-md border border-gray-300 bg-white text-gray-900 py-2 px-3 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                        <option value="">Select Role</option>
                                        @foreach($roles ?? [] as $role)
                                            <option value="{{ $role->id }}">{{ $role->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">New Password</label>
                                    <input type="password" name="password" id="edit-user-password" class="mt-1 block w-full rounded-md border border-gray-300 bg-white text-gray-900 py-2 px-3 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-primary sm:text-sm" placeholder="Leave blank to keep current password">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Confirm Password</label>
                                    <input type="password" name="password_confirmation" id="edit-user-password-confirm" class="mt-1 block w-full rounded-md border border-gray-300 bg-white text-gray-900 py-2 px-3 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-primary text-base font-medium text-white hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:ml-3 sm:w-auto sm:text-sm">
                        Update User
                    </button>
                    <button type="button" onclick="document.getElementById('edit-user-modal').classList.add('hidden')" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete User Confirmation Modal -->
<div id="delete-user-modal" data-admin-modal class="hidden fixed inset-0 z-[100] overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" onclick="document.getElementById('delete-user-modal').classList.add('hidden')"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                        <span class="material-symbols-outlined text-red-600" style="font-size: 24px;">warning</span>
                    </div>
                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left flex-1">
                        <h3 class="text-lg leading-6 font-medium text-gray-900">Delete User</h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-500">
                                Are you sure you want to delete <strong id="delete-user-name" class="text-gray-900"></strong> (<span id="delete-user-email" class="text-gray-600"></span>)? This action cannot be undone.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <form id="delete-user-form" method="POST" class="inline">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm transition-colors">
                        Delete
                    </button>
                </form>
                <button type="button" onclick="document.getElementById('delete-user-modal').classList.add('hidden')" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm transition-colors">
                    Cancel
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let searchTimeout;
function searchUsers() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(function() {
        const search = document.getElementById('user-search')?.value || '';
        const role = document.getElementById('user-role-filter')?.value || '';
        const perPage = document.getElementById('user-per-page')?.value || 15;
        
        const url = new URL('{{ route('admin.settings.users.api') }}', window.location.origin);
        url.searchParams.set('search', search);
        url.searchParams.set('role', role);
        url.searchParams.set('per_page', perPage);
        
        fetch(url, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.html) {
                document.getElementById('users-table-body').innerHTML = data.html;
            }
            if (data.total !== undefined) {
                const totalEl = document.getElementById('users-total');
                const fromEl = document.getElementById('users-from');
                const toEl = document.getElementById('users-to');
                if (totalEl) totalEl.textContent = data.total;
                if (fromEl) fromEl.textContent = (data.current_page - 1) * data.per_page + 1;
                if (toEl) toEl.textContent = Math.min(data.current_page * data.per_page, data.total);
            }
        })
        .catch(error => console.error('Error searching users:', error));
    }, 300);
}

function openEditUserModal(id, name, email, roleId) {
    const form = document.getElementById('edit-user-form');
    form.action = '{{ route("admin.settings.users.update", ":id") }}'.replace(':id', id);
    
    document.getElementById('edit-user-name').value = name || '';
    document.getElementById('edit-user-email').value = email || '';
    document.getElementById('edit-user-role').value = roleId || '';
    document.getElementById('edit-user-password').value = '';
    document.getElementById('edit-user-password-confirm').value = '';
    
    document.getElementById('edit-user-modal').classList.remove('hidden');
}

function openDeleteUserModal(id, name, email) {
    const form = document.getElementById('delete-user-form');
    form.action = '{{ route("admin.settings.users.destroy", ":id") }}'.replace(':id', id);
    
    document.getElementById('delete-user-name').textContent = name || 'this user';
    document.getElementById('delete-user-email').textContent = email || '';
    document.getElementById('delete-user-modal').classList.remove('hidden');
}
</script>
@endsection
