<?php
require_once 'includes/auth.php';
require_once 'includes/header.php';
?>

<div x-data="usersTable()" class="space-y-6">
    
    <!-- Header & Actions -->
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <h3 class="text-3xl font-medium text-gray-100">User Management</h3>
        <div class="flex items-center gap-3">
            <button class="bg-surface hover:bg-gray-700 text-gray-300 px-4 py-2 rounded-lg border border-gray-600 transition-colors">
                <i class="fas fa-download mr-2"></i> Export
            </button>
            <button class="bg-primary hover:bg-indigo-600 text-white px-4 py-2 rounded-lg shadow-lg shadow-primary/30 transition-colors">
                <i class="fas fa-plus mr-2"></i> Add User
            </button>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-surface p-4 rounded-xl border border-gray-700 flex flex-wrap items-center gap-4">
        <div class="relative flex-1 min-w-[200px]">
            <i class="fas fa-search absolute left-3 top-3 text-gray-500"></i>
            <input x-model="search" @input.debounce.300ms="fetchUsers()" type="text" placeholder="Search by username, email..." class="w-full bg-dark border border-gray-600 rounded-lg pl-10 pr-4 py-2 text-gray-300 focus:outline-none focus:border-primary">
        </div>
        
        <select x-model="filter" @change="fetchUsers()" class="bg-dark border border-gray-600 rounded-lg px-4 py-2 text-gray-300 focus:outline-none focus:border-primary">
            <option value="all">All Users</option>
            <option value="online">Online Now</option>
            <option value="banned">Banned</option>
            <option value="bot">Bots / AI</option>
            <option value="plus">PLUS Subscriber</option>
            <option value="premium">All Premium (PLUS/Boost)</option>
        </select>
        
        <div class="text-gray-400 text-sm ml-auto">
            Showing <span x-text="users.length"></span> results
        </div>
    </div>

    <!-- Data Grid -->
    <div class="bg-surface rounded-xl shadow-lg border border-gray-700 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse">
                <thead>
                    <tr class="bg-darker/50 text-gray-400 text-xs uppercase tracking-wider border-b border-gray-700">
                        <th class="p-4 font-medium">User</th>
                        <th class="p-4 font-medium">Status</th>
                        <th class="p-4 font-medium text-center">Activity</th>
                        <th class="p-4 font-medium text-center">Stats</th>
                        <th class="p-4 font-medium">Joined</th>
                        <th class="p-4 font-medium text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-700">
                    <template x-for="user in users" :key="user.id">
                        <tr class="hover:bg-dark/50 transition-colors group">
                            <td class="p-4">
                                <div class="flex items-center gap-3">
                                    <div class="relative">
                                        <img :src="user.avatar_url || 'https://ui-avatars.com/api/?name='+user.username" class="w-10 h-10 rounded-full object-cover border border-gray-600">
                                        <div x-show="user.status === 'online'" class="absolute bottom-0 right-0 w-3 h-3 bg-green-500 rounded-full border-2 border-surface"></div>
                                    </div>
                                    <div>
                                        <div class="font-medium text-white flex items-center gap-2">
                                            <span x-text="user.display_name || user.username"></span>
                                            <span x-show="user.is_seed == 1" class="px-1.5 py-0.5 rounded text-[10px] bg-secondary/20 text-secondary font-bold">BOT</span>
                                            <span x-show="user.is_plus_subscriber == 1" class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-500/20 text-indigo-400 font-bold">PLUS</span>
                                            <span x-show="user.boosted_until && new Date(user.boosted_until) > new Date()" class="px-1.5 py-0.5 rounded text-[10px] bg-pink-500/20 text-pink-500 font-bold">DIAMOND VIP</span>
                                        </div>
                                        <div class="text-xs text-gray-500" x-text="'@'+user.username"></div>
                                        <!-- Aliases Used -->
                                        <div x-show="user.aliases && user.aliases.length > 0" class="text-[10px] text-gray-400 mt-1">
                                            <i class="fas fa-ghost"></i> Also known as: <span x-text="user.aliases.join(', ')"></span>
                                        </div>
                                    </div>
                                </div>
                            </td>
                            <td class="p-4">
                                <span class="px-2 py-1 rounded-full text-xs font-medium"
                                    :class="{
                                        'bg-green-500/10 text-green-500': user.status === 'online',
                                        'bg-gray-700 text-gray-400': user.status === 'offline',
                                        'bg-red-500/10 text-red-500': user.is_banned == 1
                                    }"
                                    x-text="user.is_banned == 1 ? 'BANNED' : (user.status || 'Offline')">
                                </span>
                            </td>
                            <td class="p-4 text-center">
                                <div class="text-xs text-gray-400">Last Login</div>
                                <div class="text-sm text-gray-200" x-text="formatDate(user.last_login_at)"></div>
                            </td>
                            <td class="p-4">
                                <div class="flex justify-center gap-4 text-xs">
                                    <div class="text-center">
                                        <div class="text-gray-200 font-bold">12</div>
                                        <div class="text-gray-500">Convs</div>
                                    </div>
                                    <div class="text-center">
                                        <div class="text-gray-200 font-bold">450</div>
                                        <div class="text-gray-500">Msgs</div>
                                    </div>
                                </div>
                            </td>
                            <td class="p-4 text-sm text-gray-400" x-text="formatDate(user.created_at)"></td>
                            <td class="p-4 text-right">
                                <div class="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                    <a :href="'user_detail.php?id='+user.id" class="p-2 bg-dark rounded hover:bg-primary hover:text-white text-gray-400 transition-colors" title="View Profile">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <button @click="banUser(user)" class="p-2 bg-dark rounded hover:bg-red-600 hover:text-white text-gray-400 transition-colors" title="Ban User">
                                        <i class="fas fa-ban"></i>
                                    </button>
                                    <div class="relative" x-data="{ open: false }">
                                        <button @click="open = !open" @click.away="open = false" class="p-2 bg-dark rounded hover:bg-gray-600 text-gray-400 transition-colors">
                                            <i class="fas fa-ellipsis-v"></i>
                                        </button>
                                        <div x-show="open" class="absolute right-0 mt-2 w-48 bg-surface rounded shadow-xl border border-gray-700 z-50 py-1" x-cloak>
                                            <a href="#" class="block px-4 py-2 text-sm hover:bg-dark text-gray-300">Edit Details</a>
                                            <a href="#" class="block px-4 py-2 text-sm hover:bg-dark text-gray-300">Reset Password</a>
                                            <button @click="deleteUser(user)" class="block w-full text-left px-4 py-2 text-sm hover:bg-dark text-red-400">Delete Account</button>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </template>
                    
                    <!-- Loading State -->
                    <tr x-show="loading">
                        <td colspan="6" class="p-8 text-center text-gray-500">
                            <i class="fas fa-circle-notch fa-spin fa-2x mb-2"></i>
                            <p>Loading users...</p>
                        </td>
                    </tr>
                    
                    <!-- Empty State -->
                    <tr x-show="!loading && users.length === 0">
                        <td colspan="6" class="p-8 text-center text-gray-500">
                            <i class="fas fa-users-slash fa-2x mb-2"></i>
                            <p>No users found matching your criteria.</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <div class="p-4 border-t border-gray-700 flex justify-between items-center">
            <button @click="prevPage()" :disabled="page === 1" class="px-4 py-2 bg-dark border border-gray-600 rounded text-sm text-gray-300 hover:bg-gray-700 disabled:opacity-50">Previous</button>
            <span class="text-sm text-gray-400">Page <span x-text="page"></span></span>
            <button @click="nextPage()" class="px-4 py-2 bg-dark border border-gray-600 rounded text-sm text-gray-300 hover:bg-gray-700">Next</button>
        </div>
    </div>

</div>

<script>
function usersTable() {
    return {
        users: [],
        loading: false,
        search: '',
        filter: 'all',
        page: 1,
        limit: 20,
        
        init() {
            this.fetchUsers();
        },
        
        fetchUsers() {
            this.loading = true;
            const offset = (this.page - 1) * this.limit;
            const query = new URLSearchParams({
                limit: this.limit,
                offset: offset,
                search: this.search,
                filter: this.filter
            });
            
            fetch('/backend-php/public/api/admin/users?' + query)
                .then(res => res.json())
                .then(data => {
                    this.users = data;
                    this.loading = false;
                })
                .catch(err => {
                    console.error(err);
                    this.loading = false;
                });
        },
        
        nextPage() {
            this.page++;
            this.fetchUsers();
        },
        
        prevPage() {
            if (this.page > 1) {
                this.page--;
                this.fetchUsers();
            }
        },
        
        formatDate(dateStr) {
            if (!dateStr) return '-';
            return new Date(dateStr).toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
        },

        banUser(user) {
            if(!confirm('Are you sure you want to ban ' + user.username + '?')) return;
            // Call API
            fetch(`/backend-php/public/api/admin/users/${user.id}/ban`, { method: 'POST' })
                .then(() => {
                    showToast('User banned successfully');
                    this.fetchUsers();
                });
        },

        deleteUser(user) {
            if(!confirm('Are you sure you want to DELETE ' + user.username + '? This cannot be undone.')) return;
            fetch(`/backend-php/public/api/admin/users/${user.id}`, { method: 'DELETE' })
                .then(() => {
                    showToast('User deleted successfully');
                    this.fetchUsers();
                });
        }
    }
}
</script>

<?php require_once 'includes/footer.php'; ?>
