<?php
$title = 'Gestión de Roles - Sistema de Gestión de Proyectos';
$page_title = 'Gestión de Roles';
$current_page = 'roles';
$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 Roles y Permisos</h2>
            <div class="flex space-x-2">
                <button onclick="openCreateRoleModal()" class="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700">
                    <i class="fas fa-plus mr-2"></i>
                    Nuevo Rol
                </button>
                <button onclick="refreshRoleList()" 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-3 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-user-shield text-blue-600"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-blue-600">Total Roles</p>
                        <p class="text-lg font-semibold text-blue-900"><?= count($roles) ?></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-users text-green-600"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-green-600">Usuarios Asignados</p>
                        <p class="text-lg font-semibold text-green-900"><?= $totalUsersWithRoles ?? 0 ?></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-key text-purple-600"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-purple-600">Permisos Únicos</p>
                        <p class="text-lg font-semibold text-purple-900"><?= count($availablePermissions ?? []) ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Lista de roles -->
    <div class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
        <?php foreach ($roles as $role): ?>
        <div class="bg-white shadow rounded-lg overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-medium text-gray-900">
                        <?= htmlspecialchars($role['display_name']) ?>
                    </h3>
                    <div class="flex items-center space-x-2">
                        <?php if ($role['is_admin']): ?>
                        <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-crown mr-1"></i>
                            Admin
                        </span>
                        <?php endif; ?>
                        <?php if (isset($role['is_system']) && $role['is_system']): ?>
                        <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-cog mr-1"></i>
                            Sistema
                        </span>
                        <?php endif; ?>
                    </div>
                </div>
                <p class="text-sm text-gray-500 mt-1"><?= htmlspecialchars($role['description']) ?></p>
            </div>

            <div class="px-6 py-4">
                <!-- Información del rol -->
                <div class="flex items-center justify-between mb-4">
                    <span class="text-sm font-medium text-gray-500">Usuarios con este rol:</span>
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                        <?= $role['user_count'] ?? 0 ?>
                    </span>
                </div>

                <!-- Permisos -->
                <div class="mb-4">
                    <h4 class="text-sm font-medium text-gray-700 mb-2">Permisos:</h4>
                    <?php 
                    $permissions = json_decode($role['permissions'], true) ?? [];
                    if (empty($permissions)): 
                    ?>
                        <p class="text-xs text-gray-500 italic">Sin permisos específicos</p>
                    <?php else: ?>
                        <div class="flex flex-wrap gap-1">
                            <?php foreach (array_slice($permissions, 0, 3) as $permission): ?>
                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">
                                <?= htmlspecialchars($permission) ?>
                            </span>
                            <?php endforeach; ?>
                            <?php if (count($permissions) > 3): ?>
                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-600">
                                +<?= count($permissions) - 3 ?> más
                            </span>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Acciones -->
                <div class="flex justify-between items-center pt-4 border-t border-gray-100">
                    <div class="flex space-x-2">
                        <button onclick="editRole(<?= $role['id'] ?>)" 
                                class="text-indigo-600 hover:text-indigo-900 text-sm">
                            <i class="fas fa-edit mr-1"></i>
                            Editar
                        </button>
                        <button onclick="viewPermissions(<?= $role['id'] ?>)" 
                                class="text-green-600 hover:text-green-900 text-sm">
                            <i class="fas fa-eye mr-1"></i>
                            Ver Permisos
                        </button>
                    </div>
                    <?php if (!isset($role['is_system']) || !$role['is_system']): ?>
                    <button onclick="deleteRole(<?= $role['id'] ?>)" 
                            class="text-red-600 hover:text-red-900 text-sm">
                        <i class="fas fa-trash mr-1"></i>
                        Eliminar
                    </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Modal para crear/editar rol -->
<div id="role-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-10 mx-auto p-5 border w-full max-w-2xl shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <h3 id="role-modal-title" class="text-lg font-medium text-gray-900 mb-4">Crear Nuevo Rol</h3>
            
            <form id="role-form">
                <input type="hidden" id="role-id" name="role_id" value="">
                <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Nombre del Rol</label>
                        <input type="text" id="role-name" name="name" required
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                               placeholder="Ej: Gerente de Proyecto">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Nombre de Sistema</label>
                        <input type="text" id="role-system-name" name="system_name" required
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                               placeholder="Ej: project_manager">
                    </div>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Descripción</label>
                    <textarea id="role-description" name="description" rows="3"
                              class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                              placeholder="Describe las responsabilidades de este rol..."></textarea>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Permisos</label>
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-2 max-h-48 overflow-y-auto border border-gray-200 rounded-lg p-3">
                        <?php 
                        $defaultPermissions = [
                            // Dashboard
                            'dashboard.view' => 'Ver Dashboard',
                            
                            // Usuarios
                            'users.view' => 'Ver Usuarios',
                            'users.manage' => 'Gestionar Usuarios',
                            'users.assign_role' => 'Asignar Roles a Usuarios',
                            
                            // Roles
                            'roles.view' => 'Ver Roles',
                            'roles.manage' => 'Gestionar Roles',
                            'roles.create' => 'Crear Roles',
                            'roles.edit' => 'Editar Roles',
                            'roles.delete' => 'Eliminar Roles',
                            
                            // Proyectos (Sprint futuro)
                            'projects.view' => 'Ver Proyectos',
                            'projects.create' => 'Crear Proyectos',
                            'projects.edit' => 'Editar Proyectos',
                            'projects.delete' => 'Eliminar Proyectos',
                            'projects.approve' => 'Aprobar Proyectos',
                            
                            // Requerimientos
                            'requirements.view' => 'Ver Requerimientos',
                            'requirements.create' => 'Crear Requerimientos',
                            'requirements.manage' => 'Gestionar Requerimientos',
                            'requirements.classify' => 'Clasificar Requerimientos',
                            
                            // Reportes
                            'reports.view' => 'Ver Reportes',
                            'reports.export' => 'Exportar Reportes',
                            
                            // Configuración
                            'settings.view' => 'Ver Configuración',
                            'settings.edit' => 'Editar Configuración',
                            
                            // Administrativos
                            'admin.full' => 'Administrador Completo',
                            'system.maintenance' => 'Modo Mantenimiento'
                        ];
                        
                        foreach ($defaultPermissions as $perm => $label): ?>
                        <label class="flex items-center space-x-2 text-sm">
                            <input type="checkbox" name="permissions[]" value="<?= $perm ?>" 
                                   class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                            <span><?= htmlspecialchars($label) ?></span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="mb-4 flex items-center space-x-6">
                    <label class="flex items-center space-x-2">
                        <input type="checkbox" id="role-is-admin" name="is_admin" 
                               class="rounded border-gray-300 text-red-600 focus:ring-red-500">
                        <span class="text-sm font-medium text-red-600">¿Es rol de administrador?</span>
                    </label>
                </div>

                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeRoleModal()" 
                            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">
                        Guardar Rol
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal para ver permisos -->
<div id="permissions-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-lg shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <h3 id="permissions-modal-title" class="text-lg font-medium text-gray-900 mb-4">Permisos del Rol</h3>
            
            <div id="permissions-list" class="space-y-2 max-h-64 overflow-y-auto">
                <!-- Los permisos se cargarán aquí -->
            </div>

            <div class="flex justify-end mt-6">
                <button onclick="closePermissionsModal()" 
                        class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400">
                    Cerrar
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function openCreateRoleModal() {
    document.getElementById('role-modal-title').textContent = 'Crear Nuevo Rol';
    document.getElementById('role-form').reset();
    document.getElementById('role-id').value = '';
    document.getElementById('role-modal').classList.remove('hidden');
    
    // Generar nombre de sistema automáticamente
    document.getElementById('role-name').addEventListener('input', function() {
        const systemName = this.value.toLowerCase()
            .replace(/[^a-z0-9\s]/g, '')
            .replace(/\s+/g, '_');
        document.getElementById('role-system-name').value = systemName;
    });
}

function editRole(roleId) {
    // Obtener datos del rol
    fetch(`/admin/roles?action=get&role_id=${roleId}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const role = data.role;
            document.getElementById('role-modal-title').textContent = 'Editar Rol';
            document.getElementById('role-id').value = role.id;
            document.getElementById('role-name').value = role.display_name;
            document.getElementById('role-system-name').value = role.name;
            document.getElementById('role-description').value = role.description || '';
            document.getElementById('role-is-admin').checked = role.is_admin == 1;
            
            // Marcar permisos
            const permissions = role.permissions ? JSON.parse(role.permissions) : [];
            document.querySelectorAll('input[name="permissions[]"]').forEach(checkbox => {
                checkbox.checked = permissions.includes(checkbox.value);
            });
            
            document.getElementById('role-modal').classList.remove('hidden');
        } else {
            showToast('Error al cargar datos del rol', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('Error de conexión', 'error');
    });
}

function closeRoleModal() {
    document.getElementById('role-modal').classList.add('hidden');
}

function viewPermissions(roleId) {
    // TODO: Cargar y mostrar permisos del rol
    document.getElementById('permissions-modal-title').textContent = 'Permisos del Rol';
    document.getElementById('permissions-modal').classList.remove('hidden');
    
    // Ejemplo de permisos (esto debería venir del servidor)
    const examplePermissions = ['dashboard.view', 'projects.view', 'projects.create'];
    const permissionsList = document.getElementById('permissions-list');
    permissionsList.innerHTML = examplePermissions.map(perm => `
        <div class="flex items-center space-x-2">
            <i class="fas fa-check-circle text-green-500"></i>
            <span class="text-sm">${perm}</span>
        </div>
    `).join('');
}

function closePermissionsModal() {
    document.getElementById('permissions-modal').classList.add('hidden');
}

async function deleteRole(roleId) {
    if (!confirm('¿Estás seguro de eliminar este rol? Esta acción no se puede deshacer.')) {
        return;
    }

    try {
        const response = await fetch('/admin/roles', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'delete',
                role_id: roleId,
                csrf_token: '<?= $csrf_token ?>'
            })
        });

        const data = await response.json();

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

// Manejar envío del formulario
document.getElementById('role-form').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const roleId = document.getElementById('role-id').value;
    
    // Convertir FormData a URLSearchParams
    const params = new URLSearchParams();
    params.append('action', roleId ? 'update' : 'create');
    params.append('csrf_token', formData.get('csrf_token'));
    params.append('name', formData.get('name'));
    params.append('system_name', formData.get('system_name'));
    params.append('description', formData.get('description'));
    
    if (roleId) {
        params.append('role_id', roleId);
    }
    
    // Agregar permisos seleccionados
    const checkboxes = document.querySelectorAll('input[name="permissions[]"]:checked');
    checkboxes.forEach(checkbox => {
        params.append('permissions[]', checkbox.value);
    });
    
    // Agregar is_admin si está marcado
    if (document.getElementById('role-is-admin').checked) {
        params.append('is_admin', '1');
    }

    try {
        const response = await fetch('/admin/roles', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params
        });

        const data = await response.json();

        if (data.success) {
            showToast('Rol guardado correctamente', 'success');
            closeRoleModal();
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(data.message || 'Error al guardar rol', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showToast('Error de conexión', 'error');
    }
});

function refreshRoleList() {
    location.reload();
}
</script>

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