<?php

declare(strict_types=1);

require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/SuperAdmin/SuperAdminAuth.php';
require_once __DIR__ . '/../../src/SuperAdmin/UserManager.php';
require_once __DIR__ . '/navigation.php';

SuperAdminAuth::requirePermission('users_view');

$admin = SuperAdminAuth::getCurrentAdmin();
$canManage = SuperAdminAuth::hasPermission('users_manage');
$canBan = SuperAdminAuth::hasPermission('users_ban');
$canDelete = SuperAdminAuth::hasPermission('users_delete');
$canLoginAs = SuperAdminAuth::hasPermission('workspaces_login');

$message = '';
$error = '';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $userId = (int)($_POST['user_id'] ?? 0);

    if ($action === 'ban' && $canBan && $userId) {
        $reason = trim($_POST['reason'] ?? '');
        if (UserManager::banUser($userId, $reason)) {
            SuperAdminAuth::logActivity($admin['id'], 'ban_user', 'user', $userId, ['reason' => $reason]);
            $message = 'User banned successfully.';
        } else {
            $error = 'Failed to ban user.';
        }
    } elseif ($action === 'unban' && $canBan && $userId) {
        if (UserManager::unbanUser($userId)) {
            SuperAdminAuth::logActivity($admin['id'], 'unban_user', 'user', $userId);
            $message = 'User unbanned successfully.';
        } else {
            $error = 'Failed to unban user.';
        }
    } elseif ($action === 'delete' && $canDelete && $userId) {
        if (UserManager::deleteUser($userId)) {
            SuperAdminAuth::logActivity($admin['id'], 'delete_user', 'user', $userId);
            $message = 'User deleted successfully.';
        } else {
            $error = 'Failed to delete user.';
        }
    } elseif ($action === 'login_as' && $canLoginAs && $userId) {
        $token = UserManager::loginAsUser($userId);
        if ($token) {
            SuperAdminAuth::logActivity($admin['id'], 'login_as_user', 'user', $userId);
            // Redirect to main app with the token
            header('Location: /auth/admin-login.php?token=' . urlencode($token));
            exit;
        } else {
            $error = 'Failed to login as user.';
        }
    }
}

// Get filters
$page = max(1, (int)($_GET['page'] ?? 1));
$search = trim($_GET['search'] ?? '');
$filters = [];
if ($search) $filters['search'] = $search;
if (isset($_GET['is_banned'])) $filters['is_banned'] = (int)$_GET['is_banned'];

$userStats = UserManager::getStats();
$result = UserManager::getUsers($page, 20, $filters);
$users = $result['users'];
$totalPages = $result['total_pages'];
$total = $result['total'];

function formatAdminDate(?string $dateValue, string $emptyLabel = '—'): string
{
    if (!$dateValue) {
        return '<span class="text-slate-400">' . htmlspecialchars($emptyLabel, ENT_QUOTES) . '</span>';
    }

    $timestamp = strtotime($dateValue);
    if (!$timestamp) {
        return '<span class="text-slate-400">' . htmlspecialchars($emptyLabel, ENT_QUOTES) . '</span>';
    }

    $primary = date('jS M, y', $timestamp);
    return '<span class="text-slate-700 font-medium">' . htmlspecialchars($primary, ENT_QUOTES) . '</span>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Users · Keelance Admin</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 min-h-screen">
    <div class="min-h-screen flex flex-col">
        <?php renderAdminNavigation(); ?>

        <main class="flex-1">
            <div class="max-w-6xl mx-auto px-4 py-6 space-y-6">
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                    <div>
                        <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Users</h1>
                        <p class="text-slate-500 mt-1 text-sm">
                            <?= number_format($total) ?> total users across all workspaces.
                        </p>
                    </div>
                    <div class="flex items-center gap-2 text-xs text-slate-500">
                        <span class="inline-flex items-center gap-1 rounded-full border border-slate-200 bg-white px-2.5 py-1 shadow-sm">
                            <span class="h-1.5 w-1.5 rounded-full bg-blue-500"></span>
                            <span class="font-medium text-slate-700">User directory</span>
                        </span>
                        <?php if ($search || isset($_GET['is_banned'])): ?>
                            <span class="hidden sm:inline text-xs text-slate-400">
                                Filtered view
                            </span>
                        <?php else: ?>
                            <span class="hidden sm:inline text-xs text-slate-400">
                                All users · page <?= $page ?> of <?= $totalPages ?: 1 ?>
                            </span>
                        <?php endif; ?>
                    </div>
                </div>

    <?php if ($message): ?>
        <div class="bg-emerald-50 border border-emerald-200 rounded-lg p-4 mb-6">
            <p class="text-sm text-emerald-700"><?= htmlspecialchars($message) ?></p>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <p class="text-sm text-red-700"><?= htmlspecialchars($error) ?></p>
        </div>
    <?php endif; ?>

    <!-- Snapshot -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <?php
            $snapshots = [
                ['label' => 'Total Users', 'value' => number_format($userStats['total_users'] ?? $total), 'chip' => '+'.number_format($userStats['registered_this_month'] ?? 0).' this month', 'color' => 'from-slate-50 to-white'],
                ['label' => 'Active', 'value' => number_format($userStats['active_users'] ?? 0), 'chip' => ($userStats['active_users'] ?? 0) ? round(($userStats['active_users'] / max(1, $userStats['total_users'])) * 100).'%' : '0%', 'color' => 'from-emerald-50 to-white'],
                ['label' => 'Banned', 'value' => number_format($userStats['banned_users'] ?? 0), 'chip' => ($userStats['banned_users'] ?? 0) ? round(($userStats['banned_users'] / max(1, $userStats['total_users'])) * 100).'%' : '0%', 'color' => 'from-rose-50 to-white'],
                ['label' => 'Registered · 7d', 'value' => number_format($userStats['registered_this_week'] ?? 0), 'chip' => 'Last 7 days', 'color' => 'from-blue-50 to-white'],
            ];
        ?>
        <?php foreach ($snapshots as $card): ?>
            <div class="rounded-2xl border border-slate-200 bg-gradient-to-br <?= $card['color'] ?> p-4 shadow-sm">
                <p class="text-xs uppercase tracking-wide text-slate-500 font-semibold"><?= $card['label'] ?></p>
                <div class="flex items-center justify-between mt-2">
                    <p class="text-2xl font-semibold text-slate-900"><?= $card['value'] ?></p>
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-medium bg-white/70 border border-slate-200 text-slate-600">
                        <?= htmlspecialchars($card['chip']) ?>
                    </span>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm space-y-4">
        <div class="flex flex-wrap items-center gap-3">
            <div class="flex items-center gap-2 text-sm text-slate-500">
                <span class="inline-flex items-center justify-center w-8 h-8 rounded-full bg-slate-100 text-slate-600">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6a4 4 0 100 8 4 4 0 000-8zM16 16l4 4" /></svg>
                </span>
                <span>Filter users</span>
            </div>
            <?php if ($search || isset($_GET['is_banned'])): ?>
                <span class="inline-flex items-center gap-1 text-xs font-medium text-blue-700 bg-blue-50 border border-blue-100 px-2.5 py-0.5 rounded-full">
                    <?= $search ? 'Search: "'.htmlspecialchars($search).'"' : 'Status filter active' ?>
                </span>
            <?php endif; ?>
        </div>
        <form method="GET" class="flex flex-wrap gap-3">
            <div class="flex-1 min-w-[220px]">
                <input type="text" name="search" value="<?= htmlspecialchars($search) ?>"
                       placeholder="Search by name, email, or workspace..."
                       class="w-full px-4 py-2.5 bg-white border border-slate-300 rounded-lg text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <select name="is_banned" class="px-4 py-2.5 bg-white border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">All Status</option>
                    <option value="0" <?= isset($_GET['is_banned']) && $_GET['is_banned'] === '0' ? 'selected' : '' ?>>Active</option>
                    <option value="1" <?= isset($_GET['is_banned']) && $_GET['is_banned'] === '1' ? 'selected' : '' ?>>Banned</option>
                </select>
            </div>
            <div class="flex items-center gap-2">
                <button type="submit" class="inline-flex items-center gap-2 px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-semibold transition-colors">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg>
                    Apply
                </button>
                <?php if ($search || isset($_GET['is_banned'])): ?>
                    <a href="/admin/users.php" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg border border-slate-200 text-slate-600 text-sm font-medium hover:bg-slate-50">
                        Reset
                    </a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- Users Table -->
    <div class="bg-white rounded-2xl overflow-hidden border border-slate-200 shadow-sm">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="text-left text-xs font-semibold uppercase tracking-wide text-slate-500 border-b border-slate-200 bg-slate-50">
                        <th class="px-4 py-3">User</th>
                        <th class="px-4 py-3">Access</th>
                        <th class="px-4 py-3">Status</th>
                        <th class="px-4 py-3">Activity</th>
                        <th class="px-4 py-3 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php foreach ($users as $user): ?>
                        <tr class="hover:bg-slate-50/60">
                            <td class="px-4 py-4">
                                <div class="space-y-1">
                                    <p class="font-semibold text-slate-900">
                                        <?= htmlspecialchars($user['name']) ?>
                                    </p>
                                    <p class="text-slate-500 text-sm"><?= htmlspecialchars($user['email']) ?></p>
                                </div>
                            </td>
                            <td class="px-4 py-4 text-slate-600 text-sm">
                                <?= $user['workspace_count'] ?> workspaces
                            </td>
                            <td class="px-4 py-4">
                                <?php if ($user['is_banned']): ?>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-700">
                                        Banned
                                    </span>
                                <?php elseif ($user['is_active']): ?>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-700">
                                        Active
                                    </span>
                                <?php else: ?>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-600">
                                        Inactive
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-4 text-slate-500 text-sm">
                                <div class="space-y-1">
                                    <div class="flex items-center gap-2">
                                        <span class="text-slate-400">Last login</span>
                                        <?= formatAdminDate($user['last_login_at'], 'Never'); ?>
                                    </div>
                                    <div class="flex items-center gap-2 text-xs">
                                        <span class="text-slate-400">Joined</span>
                                        <?= formatAdminDate($user['created_at']); ?>
                                    </div>
                                </div>
                            </td>
                            <td class="px-4 py-4">
                                <div class="flex items-center justify-end gap-2">
                                    <?php if ($canLoginAs && !$user['is_banned']): ?>
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="action" value="login_as">
                                            <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                            <button type="submit" class="w-8 h-8 inline-flex items-center justify-center rounded-full border border-blue-200 text-blue-600 bg-white hover:bg-blue-50 transition-colors" title="Login as user">
                                                <span class="sr-only">Login as user</span>
                                                <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                    <path d="M10 17l5-5-5-5" />
                                                    <path d="M15 12H3" />
                                                    <path d="M19 21V3" />
                                                </svg>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    
                                    <?php if ($canBan): ?>
                                        <?php if ($user['is_banned']): ?>
                                            <form method="POST" class="inline">
                                                <input type="hidden" name="action" value="unban">
                                                <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                                <button type="submit" class="w-8 h-8 inline-flex items-center justify-center rounded-full border border-emerald-200 text-emerald-600 bg-white hover:bg-emerald-50 transition-colors" title="Unban user">
                                                    <span class="sr-only">Unban user</span>
                                                    <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                        <path d="M9 11l3 3L22 4" />
                                                        <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />
                                                    </svg>
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <button onclick="showBanModal(<?= $user['id'] ?>, '<?= htmlspecialchars($user['name'], ENT_QUOTES) ?>')"
                                                    class="w-8 h-8 inline-flex items-center justify-center rounded-full border border-amber-200 text-amber-600 bg-white hover:bg-amber-50 transition-colors" title="Ban user">
                                                <span class="sr-only">Ban user</span>
                                                <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                    <circle cx="12" cy="12" r="10" />
                                                    <line x1="4" y1="4" x2="20" y2="20" />
                                                </svg>
                                            </button>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                    
                                    <?php if ($canDelete): ?>
                                        <form method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this user? This cannot be undone.')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                            <button type="submit" class="w-8 h-8 inline-flex items-center justify-center rounded-full border border-red-200 text-red-600 bg-white hover:bg-red-50 transition-colors" title="Delete user">
                                                <span class="sr-only">Delete user</span>
                                                <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                    <polyline points="3 6 5 6 21 6" />
                                                    <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
                                                    <path d="M10 11v6" />
                                                    <path d="M14 11v6" />
                                                    <path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
                                                </svg>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if (empty($users)): ?>
            <div class="text-center py-12">
                <p class="text-slate-400">No users found</p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
        <div class="flex justify-center gap-2 mt-6">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?><?= isset($_GET['is_banned']) ? '&is_banned=' . $_GET['is_banned'] : '' ?>"
                   class="px-4 py-2 rounded-full text-sm <?= $i === $page
                        ? 'bg-blue-600 border border-blue-600 text-white'
                        : 'bg-white border border-slate-200 text-slate-600 hover:bg-slate-50' ?>">
                    <?= $i ?>
                </a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
        </main>

<!-- Ban Modal -->
<div id="banModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-slate-800 rounded-xl p-6 w-full max-w-md mx-4">
        <h3 class="text-lg font-semibold mb-4">Ban User</h3>
        <form method="POST">
            <input type="hidden" name="action" value="ban">
            <input type="hidden" name="user_id" id="banUserId">
            <p class="text-slate-400 mb-4">Are you sure you want to ban <span id="banUserName" class="text-white font-medium"></span>?</p>
            <div class="mb-4">
                <label class="block text-sm text-slate-400 mb-2">Reason (optional)</label>
                <textarea name="reason" rows="3" class="w-full px-4 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
            </div>
            <div class="flex gap-3">
                <button type="button" onclick="closeBanModal()" class="flex-1 px-4 py-2 bg-slate-700 hover:bg-slate-600 rounded-lg transition-colors">
                    Cancel
                </button>
                <button type="submit" class="flex-1 px-4 py-2 bg-red-600 hover:bg-red-700 rounded-lg transition-colors">
                    Ban User
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function showBanModal(userId, userName) {
    document.getElementById('banUserId').value = userId;
    document.getElementById('banUserName').textContent = userName;
    document.getElementById('banModal').classList.remove('hidden');
    document.getElementById('banModal').classList.add('flex');
}

function closeBanModal() {
    document.getElementById('banModal').classList.add('hidden');
    document.getElementById('banModal').classList.remove('flex');
}
</script>

<?php renderAdminFooter(); ?>
</body>
</html>
