@extends('layouts.app')
@section('content')
<div class="container-fluid py-3">
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-success text-white py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-users me-2"></i>User Management</h5>
                    @if(Auth::user()->hasPermission('users.create'))
                    <a href="{{ route('users.create') }}" class="btn btn-light btn-sm">
                        <i class="fas fa-plus me-1"></i> Add New User
                    </a>
                    @endif
                </div>
                <div class="card-body">
                    <!-- Search Form (Optional - can be added if needed) -->
                    <form method="GET" action="{{ route('users.index') }}" class="mb-4">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="search" class="form-label"><strong>Search Users</strong></label>
                                <input type="text" class="form-control" id="search" name="search"
                                       value="{{ request('search') }}" placeholder="Search by name or email...">
                            </div>
                            <div class="col-md-6">
                                <label for="role" class="form-label"><strong>Role</strong></label>
                                <select class="form-control" id="role" name="role">
                                    <option value="">All Roles</option>
                                    <option value="admin" {{ request('role') == 'admin' ? 'selected' : '' }}>Admin</option>
                                    <option value="loan_officer" {{ request('role') == 'loan_officer' ? 'selected' : '' }}>Loan Officer</option>
                                    <option value="auditor" {{ request('role') == 'auditor' ? 'selected' : '' }}>Auditor</option>
                                </select>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-12">
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-search"></i> Search
                                </button>
                                <a href="{{ route('users.index') }}" class="btn btn-outline-secondary">
                                    <i class="fas fa-times"></i> Clear
                                </a>
                            </div>
                        </div>
                    </form>

                    @if($users->isEmpty())
                    <div class="text-center py-5">
                        <i class="fas fa-users fa-3x text-muted mb-3"></i>
                        <h4 class="text-muted mb-3">No Users Found</h4>
                        <p class="text-muted mb-4">Get started by creating your first user account.</p>
                        @if(Auth::user()->hasPermission('users.create'))
                        <a href="{{ route('users.create') }}" class="btn btn-success">
                            <i class="fas fa-plus me-1"></i> Add New User
                        </a>
                        @endif
                    </div>
                    @else
                    <!-- Results Table -->
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead class="bg-success text-white">
                                <tr>
                                    <th>ID</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Role</th>
                                    <th>Created At</th>
                                    <th style="width:130px">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($users as $user)
                                <tr>
                                    <td>{{ $user->id }}</td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="user-avatar me-2" style="width: 32px; height: 32px; background: #198754; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 0.8rem;">
                                                {{ strtoupper(substr($user->name, 0, 1)) }}
                                            </div>
                                            <span>{{ $user->name }}</span>
                                        </div>
                                    </td>
                                    <td>{{ $user->email }}</td>
                                    <td>
                                        @php
                                            $badgeColor = 'secondary';
                                            if ($user->role === 'admin') $badgeColor = 'success';
                                            elseif ($user->role === 'loan_officer') $badgeColor = 'info';
                                            elseif ($user->role === 'auditor') $badgeColor = 'warning';
                                        @endphp
                                        <span class="badge bg-{{ $badgeColor }}">
                                            {{ ucfirst($user->role) }}
                                        </span>
                                    </td>
                                    <td>{{ $user->created_at->format('Y-m-d') }}</td>
                                    <td class="text-center">
                                        @if(Auth::user()->hasPermission('users.edit'))
                                        <a href="{{ route('users.edit', $user) }}"
                                           class="btn btn-sm btn-success" title="Edit User">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        @endif
                                        @if(Auth::user()->hasPermission('permissions.manage', 'manage'))
                                        <a href="{{ route('permissions.user', $user) }}"
                                           class="btn btn-sm btn-primary ms-1" title="Manage Permissions">
                                            <i class="fas fa-key"></i>
                                        </a>
                                        @endif
                                        @if(Auth::user()->hasPermission('users.delete') && $user->id !== Auth::id())
                                        <button class="btn btn-sm btn-danger ms-1 deleteBtn"
                                                data-id="{{ $user->id }}"
                                                data-name="{{ $user->name }}" title="Delete User">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                        @endif
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <div class="mt-3">
                        {{ $users->appends(request()->query())->links() }}
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Confirm Deletion</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete user <strong id="userNameDisplay"></strong>?</p>
                <p class="text-danger"><small>This action cannot be undone and will permanently remove the user account.</small></p>
            </div>
            <div class="modal-footer">
                <button id="cancelDeleteBtn" type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <form id="deleteForm" method="POST" action="" style="display: inline;">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const deleteButtons = document.querySelectorAll('.deleteBtn');
    const deleteForm = document.getElementById('deleteForm');
    const userNameDisplay = document.getElementById('userNameDisplay');
    const modal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));

    deleteButtons.forEach(button => {
        button.addEventListener('click', function() {
            const userId = this.getAttribute('data-id');
            const userName = this.getAttribute('data-name');
            const actionUrl = "{{ route('users.destroy', ':id') }}".replace(':id', userId);

            userNameDisplay.textContent = userName;
            deleteForm.action = actionUrl;
            modal.show();
        });
    });

    // Close modal when cancel button is clicked
    document.getElementById('cancelDeleteBtn').addEventListener('click', function() {
        modal.hide();
    });

    // Optional: Add smooth hover effects
    const tableRows = document.querySelectorAll('tbody tr');
    tableRows.forEach(row => {
        row.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-1px)';
            this.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)';
        });

        row.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = 'none';
        });
    });
});
</script>

<style>
.card {
    border-radius: 8px;
    overflow: hidden;
    border: none;
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
}
.card-header {
    border-bottom: 1px solid rgba(0,0,0,0.1);
}
.table th {
    background-color: #f8f9fa;
}
.badge {
    padding: 5px 10px;
    border-radius: 4px;
    font-size: 0.85em;
}
.pagination {
    margin-bottom: 0;
}
.btn-light {
    background-color: #fff;
    border-color: #fff;
    color: #198754;
}
.btn-light:hover {
    background-color: #f8f9fa;
    border-color: #f8f9fa;
    color: #198754;
}
</style>
@endsection
