<?php
$title = 'Gestión de Usuarios - Sistema de Gestión de Proyectos';
$page_title = 'Gestión de Usuarios';
$current_page = 'users';
$showSidebar = true;
$csrf_token = csrf_token();

ob_start();
?>

<div class="mb-6">
    <!-- Header con estadísticas -->
    <div class="bg-white shadow rounded-lg p-6 mb-6">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-xl font-semibold text-gray-900">Gestión de Usuarios</h2>
            <div class="flex space-x-2">
                <button onclick="openInviteUserModal()" class="inline-flex items-center px-3 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700">
                    <i class="fas fa-user-plus mr-2"></i>
                    Invitar Usuario
                </button>
                <button onclick="refreshUserList()" class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                    <i class="fas fa-sync-alt mr-2"></i>
                    Actualizar
                </button>
            </div>
        </div>

        <!-- Estadísticas rápidas -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div class="bg-blue-50 p-4 rounded-lg">
                <div class="flex items-center">
                    <div class="p-2 bg-blue-100 rounded-lg">
                        <i class="fas fa-users text-blue-600"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-blue-600">Total</p>
                        <p class="text-lg font-semibold text-blue-900" id="total-users"><?= count($users) ?></p>
                    </div>
                </div>
            </div>

            <div class="bg-green-50 p-4 rounded-lg">
                <div class="flex items-center">
                    <div class="p-2 bg-green-100 rounded-lg">
                        <i class="fas fa-user-check text-green-600"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-green-600">Activos</p>
                        <p class="text-lg font-semibold text-green-900" id="active-users">
                            <?= count(array_filter($users, fn($u) => $u['is_active'])) ?>
                        </p>
                    </div>
                </div>
            </div>

            <div class="bg-yellow-50 p-4 rounded-lg">
                <div class="flex items-center">
                    <div class="p-2 bg-yellow-100 rounded-lg">
                        <i class="fas fa-user-clock text-yellow-600"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-yellow-600">Pendientes</p>
                        <p class="text-lg font-semibold text-yellow-900" id="pending-users">
                            <?= count(array_filter($users, fn($u) => !$u['is_active'] || !$u['role_id'])) ?>
                        </p>
                    </div>
                </div>
            </div>

            <div class="bg-purple-50 p-4 rounded-lg">
                <div class="flex items-center">
                    <div class="p-2 bg-purple-100 rounded-lg">
                        <i class="fas fa-user-shield text-purple-600"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-purple-600">Admins</p>
                        <p class="text-lg font-semibold text-purple-900" id="admin-users">
                            <?= count(array_filter($users, fn($u) => $u['is_admin'])) ?>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtros y búsqueda -->
    <div class="bg-white shadow rounded-lg p-4 mb-6">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div class="flex items-center space-x-4">
                <div class="relative">
                    <input type="text" id="search-users" placeholder="Buscar usuarios..." 
                           class="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                </div>
                
                <select id="filter-status" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                    <option value="">Todos los estados</option>
                    <option value="active">Activos</option>
                    <option value="inactive">Inactivos</option>
                    <option value="pending">Pendientes</option>
                </select>

                <select id="filter-role" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                    <option value="">Todos los roles</option>
                    <?php foreach ($roles as $role): ?>
                    <option value="<?= $role['id'] ?>"><?= htmlspecialchars($role['display_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
    </div>

    <!-- Tabla de usuarios -->
    <div class="bg-white shadow rounded-lg overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">Lista de Usuarios</h3>
        </div>

        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200" id="users-table">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Usuario</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rol</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Estado</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Último Acceso</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Acciones</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200" id="users-tbody">
                    <?php foreach ($users as $user): ?>
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 h-10 w-10">
                                    <div class="h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center">
                                        <span class="text-sm font-medium text-blue-600">
                                            <?= strtoupper(substr($user['first_name'] ?? 'U', 0, 1)) ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="ml-4">
                                    <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>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <?php if ($user['role_id']): ?>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                    <i class="fas fa-user-shield mr-1"></i>
                                    <?= htmlspecialchars($user['role_display_name'] ?? 'Sin nombre') ?>
                                </span>
                            <?php else: ?>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                    <i class="fas fa-user-times mr-1"></i>
                                    Sin rol
                                </span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <?php if ($user['is_active'] && $user['role_id']): ?>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                    <i class="fas fa-check-circle mr-1"></i>
                                    Activo
                                </span>
                            <?php elseif ($user['is_active'] && !$user['role_id']): ?>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                    <i class="fas fa-clock mr-1"></i>
                                    Pendiente
                                </span>
                            <?php else: ?>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                    <i class="fas fa-times-circle mr-1"></i>
                                    Inactivo
                                </span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <?php if ($user['last_login']): ?>
                                <?= date('d/m/Y H:i', strtotime($user['last_login'])) ?>
                            <?php else: ?>
                                <span class="text-gray-400">Nunca</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <div class="flex justify-end space-x-2">
                                <?php if (!$user['role_id']): ?>
                                <button onclick="assignRole(<?= $user['id'] ?>)" 
                                        class="text-blue-600 hover:text-blue-900 px-2 py-1 rounded"
                                        title="Asignar rol">
                                    <i class="fas fa-user-plus"></i>
                                </button>
                                <?php endif; ?>
                                
                                <button onclick="editUser(<?= $user['id'] ?>)" 
                                        class="text-indigo-600 hover:text-indigo-900 px-2 py-1 rounded"
                                        title="Editar usuario">
                                    <i class="fas fa-edit"></i>
                                </button>
                                
                                <?php if ($user['role_name'] === 'super_admin'): ?>
                                <!-- Super admin no se puede desactivar -->
                                <button disabled 
                                        class="text-gray-400 cursor-not-allowed px-2 py-1 rounded"
                                        title="El Super Administrador no puede ser desactivado">
                                    <i class="fas fa-lock"></i>
                                </button>
                                <?php else: ?>
                                <button onclick="toggleUserStatus(<?= $user['id'] ?>, <?= $user['is_active'] ? 'false' : 'true' ?>)" 
                                        class="<?= $user['is_active'] ? 'text-red-600 hover:text-red-900' : 'text-green-600 hover:text-green-900' ?> px-2 py-1 rounded"
                                        title="<?= $user['is_active'] ? 'Desactivar usuario' : 'Activar usuario' ?>">
                                    <i class="fas fa-<?= $user['is_active'] ? 'user-slash' : 'user-check' ?>"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Fin de la tabla -->
        <div class="bg-white px-4 py-3 border-t border-gray-200 sm:px-6">
            <div class="text-sm text-gray-700">
                Total: <span class="font-medium"><?= count($users) ?></span> usuarios
            </div>
        </div>
    </div>
</div>

<!-- Modal para invitar usuario -->
<div id="invite-user-modal" class="fixed inset-0 z-50 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
    <div class="relative top-20 mx-auto p-5 border w-full max-w-md shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <h3 class="text-lg font-medium text-gray-900 mb-4">Invitar Nuevo Usuario</h3>
            
            <form id="invite-form">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Nombre *</label>
                    <input type="text" id="invite-first-name" name="first_name" required 
                           class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                           placeholder="Nombre del usuario">
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Apellido *</label>
                    <input type="text" id="invite-last-name" name="last_name" required 
                           class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                           placeholder="Apellido del usuario">
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Correo Electrónico *</label>
                    <input type="email" id="invite-email" name="email" required 
                           class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                           placeholder="usuario@ejemplo.com">
                    <p class="text-xs text-gray-500 mt-1">Se enviará un correo de invitación a esta dirección</p>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Rol (Opcional)</label>
                    <select id="invite-role" name="role_id" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                        <option value="">-- Asignar después --</option>
                        <?php foreach ($roles as $role): ?>
                        <option value="<?= $role['id'] ?>"><?= htmlspecialchars($role['display_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="text-xs text-gray-500 mt-1">El rol puede ser asignado más tarde</p>
                </div>

                <div class="mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3">
                    <div class="flex items-start">
                        <i class="fas fa-info-circle text-blue-600 mt-1 mr-2"></i>
                        <div class="text-sm text-blue-700">
                            <p class="font-medium">Proceso de invitación:</p>
                            <ul class="mt-1 ml-4 list-disc space-y-1">
                                <li>Se creará el usuario en el sistema</li>
                                <li>Se enviará un correo con enlace de activación</li>
                                <li>El usuario completará sus datos en Keycloak</li>
                                <li>Los datos se sincronizarán automáticamente</li>
                            </ul>
                        </div>
                    </div>
                </div>

                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeInviteUserModal()" 
                            class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400">
                        Cancelar
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        <i class="fas fa-paper-plane mr-2"></i>
                        Enviar Invitación
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal para asignar/editar rol -->
<div id="assign-role-modal" class="fixed inset-0 z-50 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <h3 class="text-lg font-medium text-gray-900 mb-4">Gestionar Rol de Usuario</h3>
            
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">Seleccionar Rol</label>
                <select id="role-select" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                    <option value="">-- Sin rol asignado --</option>
                    <?php foreach ($roles as $role): ?>
                    <option value="<?= $role['id'] ?>"><?= htmlspecialchars($role['display_name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <p class="text-xs text-gray-500 mt-1">Selecciona "Sin rol asignado" para eliminar el rol actual</p>
            </div>

            <div class="flex justify-end space-x-3">
                <button onclick="closeAssignRoleModal()" 
                        class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400">
                    Cancelar
                </button>
                <button onclick="confirmAssignRole()" 
                        class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                    Guardar
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let currentUserId = null;

function openInviteUserModal() {
    document.getElementById('invite-user-modal').classList.remove('hidden');
}

function closeInviteUserModal() {
    document.getElementById('invite-user-modal').classList.add('hidden');
    document.getElementById('invite-form').reset();
}

document.getElementById('invite-form').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', 'invite_user');
    formData.append('csrf_token', '<?= $csrf_token ?>');
    
    try {
        const response = await fetch('/admin/users', {
            method: 'POST',
            body: new URLSearchParams(formData)
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast(data.message || 'Invitación enviada correctamente', 'success');
            closeInviteUserModal();
            setTimeout(() => location.reload(), 1500);
        } else {
            showToast(data.message || 'Error al enviar invitación', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showToast('Error de conexión', 'error');
    }
});

function assignRole(userId) {
    currentUserId = userId;
    document.getElementById('assign-role-modal').classList.remove('hidden');
}

function closeAssignRoleModal() {
    document.getElementById('assign-role-modal').classList.add('hidden');
    currentUserId = null;
    document.getElementById('role-select').value = '';
}

async function confirmAssignRole() {
    const roleId = document.getElementById('role-select').value;
    if (!currentUserId) {
        showToast('Error: Usuario no seleccionado', 'error');
        return;
    }

    try {
        const response = await fetch('/admin/users', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'update_role',
                user_id: currentUserId,
                role_id: roleId || '', // Permite vacío para eliminar rol
                csrf_token: '<?= $csrf_token ?>'
            })
        });

        const data = await response.json();

        if (data.success) {
            showToast(roleId ? 'Rol asignado correctamente' : 'Rol eliminado correctamente', 'success');
            closeAssignRoleModal();
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(data.message || 'Error al actualizar rol', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showToast('Error de conexión', 'error');
    }
}

async function toggleUserStatus(userId, newStatus) {
    if (!confirm('¿Estás seguro de cambiar el estado de este usuario?')) return;

    try {
        const response = await fetch('/admin/users', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'toggle_status',
                user_id: userId,
                is_active: newStatus,
                csrf_token: '<?= $csrf_token ?>'
            })
        });

        const data = await response.json();

        if (data.success) {
            showToast('Estado actualizado correctamente', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(data.message || 'Error al cambiar estado', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showToast('Error de conexión', 'error');
    }
}

function editUser(userId) {
    // Reutilizar el modal de asignar rol para editar
    assignRole(userId);
}

function refreshUserList() {
    location.reload();
}

// Funcionalidad de búsqueda y filtros
document.getElementById('search-users').addEventListener('input', function() {
    // TODO: Implementar búsqueda en tiempo real
});

document.getElementById('filter-status').addEventListener('change', function() {
    // TODO: Implementar filtro de estado
});

document.getElementById('filter-role').addEventListener('change', function() {
    // TODO: Implementar filtro de rol
});
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/../layouts/app.php';
?>