<?php
require_once __DIR__ . '/../api/lib.php';
hw_require_auth(['superadmin']);

$pdo = hw_db();

// Get all users with their roles
$stmt = $pdo->query("
    SELECT u.*, r.name as role_name
    FROM users u
    LEFT JOIN user_roles ur ON u.id = ur.user_id
    LEFT JOIN roles r ON ur.role_id = r.id
    ORDER BY u.created_at DESC
");
$users = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Users Management - Superadmin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body class="bg-gray-50">
    <div class="min-h-screen flex">
        <!-- Sidebar -->
        <div class="bg-emerald-800 text-white w-64 flex-shrink-0">
            <div class="p-6">
                <h1 class="text-xl font-bold">Superadmin Panel</h1>
                <p class="text-emerald-200 text-sm mt-1">Website Management</p>
            </div>
            
            <nav class="mt-6">
                <a href="dashboard.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-tachometer-alt mr-3"></i>
                    Dashboard
                </a>
                <a href="coaches.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-users mr-3"></i>
                    Coaches
                </a>
                <a href="users.php" class="flex items-center px-6 py-3 bg-emerald-700 text-white">
                    <i class="fas fa-user-friends mr-3"></i>
                    Users
                </a>
                <a href="appointments.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-calendar mr-3"></i>
                    Appointments
                </a>
                <a href="content.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-edit mr-3"></i>
                    Content
                </a>
                <div class="border-t border-emerald-700 mt-6 pt-6">
                    <a href="/files/atasteofafricanmarketplace/api/auth/logout.php" class="flex items-center px-6 py-3 hover:bg-red-600 text-emerald-100">
                        <i class="fas fa-sign-out-alt mr-3"></i>
                        Logout
                    </a>
                </div>
            </nav>
        </div>

        <!-- Main Content -->
        <div class="flex-1 p-8">
            <div class="mb-8">
                <h1 class="text-3xl font-bold text-gray-900">Users Management</h1>
                <p class="text-gray-600 mt-2">Manage all registered users</p>
            </div>

            <!-- Users Table -->
            <div class="bg-white rounded-lg shadow">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h2 class="text-lg font-semibold text-gray-900">All Users (<?= count($users) ?>)</h2>
                </div>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">User</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Role</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Joined</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($users as $user): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div>
                                        <div class="text-sm font-medium text-gray-900">
                                            <?= htmlspecialchars(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')) ?>
                                        </div>
                                        <div class="text-sm text-gray-500"><?= htmlspecialchars($user['email']) ?></div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php
                                    $roleColors = [
                                        'superadmin' => 'bg-red-100 text-red-800',
                                        'admin' => 'bg-purple-100 text-purple-800',
                                        'coach' => 'bg-emerald-100 text-emerald-800',
                                        'client' => 'bg-blue-100 text-blue-800'
                                    ];
                                    $colorClass = $roleColors[$user['role_name']] ?? 'bg-gray-100 text-gray-800';
                                    ?>
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?= $colorClass ?>">
                                        <?= ucfirst($user['role_name'] ?? 'client') ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php
                                    $statusColors = [
                                        'active' => 'bg-green-100 text-green-800',
                                        'pending' => 'bg-yellow-100 text-yellow-800',
                                        'disabled' => 'bg-red-100 text-red-800'
                                    ];
                                    $statusColor = $statusColors[$user['status']] ?? 'bg-gray-100 text-gray-800';
                                    ?>
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?= $statusColor ?>">
                                        <?= ucfirst($user['status']) ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?= date('M j, Y', strtotime($user['created_at'])) ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <button onclick="editUser(<?= $user['id'] ?>)" class="text-blue-600 hover:text-blue-900 mr-3">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button onclick="toggleStatus(<?= $user['id'] ?>, '<?= $user['status'] ?>')" class="text-orange-600 hover:text-orange-900 mr-3">
                                        <i class="fas fa-toggle-<?= $user['status'] === 'active' ? 'on' : 'off' ?>"></i>
                                    </button>
                                    <button onclick="deleteUser(<?= $user['id'] ?>)" class="text-red-600 hover:text-red-900">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        function editUser(id) {
            // Redirect to edit page or open modal
            window.location.href = `users.php?edit=${id}`;
        }

        function toggleStatus(id, currentStatus) {
            const newStatus = currentStatus === 'active' ? 'disabled' : 'active';
            if (confirm(`${newStatus === 'active' ? 'Activate' : 'Disable'} this user?`)) {
                fetch('/files/atasteofafricanmarketplace/api/admin/toggle-user-status.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id, status: newStatus })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('Error updating user status');
                    }
                });
            }
        }

        function deleteUser(id) {
            if (confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
                fetch('/files/atasteofafricanmarketplace/api/admin/delete-user.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('Error deleting user');
                    }
                });
            }
        }
    </script>
</body>
</html>