<?php
require_once '../includes/init.php';

// Check admin access
if (!isAuthenticated() || !$_SESSION['is_admin']) {
    redirect(APP_URL . '/login.php');
}

$pageTitle = 'Manage Users';
$db = getDB();

// Get filter and search
$filter = $_GET['filter'] ?? 'all';
$search = sanitizeInput($_GET['search'] ?? '');

// Build query
$sql = "SELECT * FROM users WHERE is_admin = 0";
$params = [];

if ($filter === 'pending') {
    $sql .= " AND status = 'pending'";
} elseif ($filter === 'approved') {
    $sql .= " AND status = 'approved'";
} elseif ($filter === 'blocked') {
    $sql .= " AND status = 'blocked'";
}

if ($search) {
    $sql .= " AND (name LIKE ? OR email LIKE ? OR unique_id LIKE ? OR mobile LIKE ?)";
    $searchTerm = '%' . $search . '%';
    $params = [$searchTerm, $searchTerm, $searchTerm, $searchTerm];
}

$sql .= " ORDER BY created_at DESC";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();

// Get statistics
$stats = [
    'all' => $db->query("SELECT COUNT(*) FROM users WHERE is_admin = 0")->fetchColumn(),
    'pending' => $db->query("SELECT COUNT(*) FROM users WHERE is_admin = 0 AND status = 'pending'")->fetchColumn(),
    'approved' => $db->query("SELECT COUNT(*) FROM users WHERE is_admin = 0 AND status = 'approved'")->fetchColumn(),
    'blocked' => $db->query("SELECT COUNT(*) FROM users WHERE is_admin = 0 AND status = 'blocked'")->fetchColumn()
];

include '../includes/header.php';
?>

<div class="min-h-screen bg-slate-50 dark:bg-slate-900">
    <!-- Admin Header -->
    <header class="bg-white dark:bg-slate-800 border-b border-slate-200 dark:border-slate-700 sticky top-0 z-20">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex items-center justify-between h-16">
                <div class="flex items-center gap-4">
                    <a href="dashboard.php" class="text-slate-600 dark:text-slate-400 hover:text-primary">
                        <span class="material-symbols-outlined">arrow_back</span>
                    </a>
                    <div class="text-primary flex items-center gap-2">
                        <span class="material-symbols-outlined text-2xl">people</span>
                        <span class="font-bold text-lg">Manage Users</span>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Messages -->
        <?php if (isset($_GET['message'])): ?>
        <div class="bg-green-100 dark:bg-green-900/20 border border-green-200 dark:border-green-800 text-green-700 dark:text-green-400 px-4 py-3 rounded-xl mb-6">
            <?php echo htmlspecialchars($_GET['message']); ?>
        </div>
        <?php endif; ?>
        <?php if (isset($_GET['error'])): ?>
        <div class="bg-red-100 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-400 px-4 py-3 rounded-xl mb-6">
            <?php echo htmlspecialchars($_GET['error']); ?>
        </div>
        <?php endif; ?>

        <!-- Filter Tabs -->
        <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-2 mb-6">
            <div class="flex flex-wrap gap-2">
                <a href="?filter=all" class="px-4 py-2 rounded-lg text-sm font-medium <?php echo $filter === 'all' ? 'bg-primary text-white' : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700'; ?>">
                    All Users (<?php echo $stats['all']; ?>)
                </a>
                <a href="?filter=pending" class="px-4 py-2 rounded-lg text-sm font-medium <?php echo $filter === 'pending' ? 'bg-amber-500 text-white' : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700'; ?>">
                    Pending (<?php echo $stats['pending']; ?>)
                </a>
                <a href="?filter=approved" class="px-4 py-2 rounded-lg text-sm font-medium <?php echo $filter === 'approved' ? 'bg-green-500 text-white' : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700'; ?>">
                    Approved (<?php echo $stats['approved']; ?>)
                </a>
                <a href="?filter=blocked" class="px-4 py-2 rounded-lg text-sm font-medium <?php echo $filter === 'blocked' ? 'bg-red-500 text-white' : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700'; ?>">
                    Blocked (<?php echo $stats['blocked']; ?>)
                </a>
            </div>
        </div>

        <!-- Search -->
        <div class="mb-6">
            <form method="GET" action="" class="relative max-w-md">
                <input type="hidden" name="filter" value="<?php echo $filter; ?>">
                <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">search</span>
                <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                    class="w-full pl-12 pr-4 py-3 rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-primary/50"
                    placeholder="Search users by name, email, or ID...">
                <?php if ($search): ?>
                <a href="?filter=<?php echo $filter; ?>" class="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                    <span class="material-symbols-outlined">close</span>
                </a>
                <?php endif; ?>
            </form>
        </div>

        <!-- Users Table -->
        <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-slate-50 dark:bg-slate-700/50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase">User</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase">Contact</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase">Status</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase">Joined</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-200 dark:divide-slate-700">
                        <?php if (empty($users)): ?>
                        <tr>
                            <td colspan="5" class="px-4 py-8 text-center text-slate-500">
                                No users found
                            </td>
                        </tr>
                        <?php else: ?>
                            <?php foreach ($users as $user): ?>
                            <tr class="hover:bg-slate-50 dark:hover:bg-slate-700/50">
                                <td class="px-4 py-3">
                                    <div class="flex items-center gap-3">
                                        <?php if ($user['profile_photo']): ?>
                                        <img src="../uploads/images/<?php echo htmlspecialchars($user['profile_photo']); ?>" class="w-10 h-10 rounded-full object-cover">
                                        <?php else: ?>
                                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                                            <?php if ($user['status'] === 'blocked'): ?>
                                            <div class="flex items-center gap-2">
                                                <span class="px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400">
                                                    Blocked
                                                </span>
                                                <span class="text-xs text-slate-500 dark:text-slate-400">
                                                    Last seen: <?php echo $user['last_seen'] ? date('M j, g:i A', strtotime($user['last_seen'])) : 'Never'; ?>
                                                </span>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        <?php endif; ?>
                                        <div>
                                            <p class="font-medium text-slate-900 dark:text-white"><?php echo htmlspecialchars($user['name']); ?></p>
                                            <p class="text-sm text-slate-500">@<?php echo htmlspecialchars($user['unique_id']); ?></p>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-4 py-3">
                                    <p class="text-sm text-slate-600 dark:text-slate-400"><?php echo htmlspecialchars($user['email']); ?></p>
                                    <p class="text-sm text-slate-500"><?php echo htmlspecialchars($user['mobile']); ?></p>
                                </td>
                                <td class="px-4 py-3">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                        <?php echo $user['status'] === 'approved' ? 'bg-green-100 text-green-800' : ($user['status'] === 'pending' ? 'bg-amber-100 text-amber-800' : 'bg-red-100 text-red-800'); ?>">
                                        <?php echo ucfirst($user['status']); ?>
                                    </span>
                                </td>
                                <td class="px-4 py-3 text-sm text-slate-600 dark:text-slate-400">
                                    <?php echo formatDateTime($user['created_at']); ?>
                                </td>
                                <td class="px-4 py-3">
                                    <div class="flex gap-2">
                                        <?php if ($user['status'] === 'pending'): ?>
                                        <form method="POST" action="user-action.php" class="inline">
                                            <input type="hidden" name="action" value="approve">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <button type="submit" class="p-2 text-green-600 hover:bg-green-100 rounded-lg" title="Approve">
                                                <span class="material-symbols-outlined">check</span>
                                            </button>
                                        </form>
                                        <form method="POST" action="user-action.php" class="inline">
                                            <input type="hidden" name="action" value="reject">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <button type="submit" class="p-2 text-red-600 hover:bg-red-100 rounded-lg" title="Reject">
                                                <span class="material-symbols-outlined">close</span>
                                            </button>
                                        </form>
                                        <?php elseif ($user['status'] === 'approved'): ?>
                                        <form method="POST" action="user-action.php" class="inline" onsubmit="return confirm('Block this user?')">
                                            <input type="hidden" name="action" value="block">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <button type="submit" class="p-2 text-amber-600 hover:bg-amber-100 rounded-lg" title="Block">
                                                <span class="material-symbols-outlined">block</span>
                                            </button>
                                        </form>
                                        <form method="POST" action="user-action.php" class="inline" onsubmit="return confirm('Force logout this user from all devices?')">
                                            <input type="hidden" name="action" value="force_logout">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <button type="submit" class="p-2 text-blue-600 hover:bg-blue-100 rounded-lg" title="Force Logout">
                                                <span class="material-symbols-outlined">logout</span>
                                            </button>
                                        </form>
                                        <?php else: ?>
                                        <form method="POST" action="user-action.php" class="inline" onsubmit="return confirm('Are you sure you want to unblock this user? They will be able to login again.')">
                                            <input type="hidden" name="action" value="unblock">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <button type="submit" class="p-2 text-green-600 hover:bg-green-100 rounded-lg transition-colors" title="Unblock">
                                                <span class="material-symbols-outlined">check_circle</span>
                                            </button>
                                        </form>
                                        <form method="POST" action="user-action.php" class="inline" onsubmit="return confirm('Delete this user permanently? This action cannot be undone.')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <button type="submit" class="p-2 text-red-600 hover:bg-red-100 rounded-lg transition-colors" title="Delete">
                                                <span class="material-symbols-outlined">delete</span>
                                            </button>
                                        </form>
                                        <?php endif; ?>
                                        <a href="view-chats.php?user=<?php echo $user['id']; ?>" class="p-2 text-slate-600 hover:bg-slate-100 rounded-lg" title="View Chats">
                                            <span class="material-symbols-outlined">chat</span>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>

<?php $hideFooter = true; include '../includes/footer.php'; ?>
