{% extends "base.html" %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1>Manage Users</h1>
    <a href="{{ url_for('admin_add_user') }}" class="btn btn-success">Add New User</a>
</div>
<table class="table table-striped">
    <thead>
        <tr>
            <th>ID</th>
            <th>Username</th>
            <th>Role</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        {% for user in users %}
        <tr>
            <td>{{ user.id }}</td>
            <td>{{ user.username }}</td>
            <td>
                <select class="form-select form-select-sm change-role" data-user-id="{{ user.id }}">
                    <option value="user" {% if user.role == 'user' %}selected{% endif %}>User</option>
                    <option value="admin" {% if user.role == 'admin' %}selected{% endif %}>Admin</option>
                    <option value="advanced" {% if user.role == 'advanced' %}selected{% endif %}>Advanced</option>
                </select>
            </td>
            <td>
                <form method="POST" action="{{ url_for('admin_delete_user', user_id=user.id) }}" style="display:inline;">
                    <td>
    <button class="btn btn-danger btn-sm delete-user" data-user-id="{{ user.id }}">Delete</button>
</td>

                </form>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>
<a href="{{ url_for('admin_dashboard') }}" class="btn btn-secondary mt-3">Back to Dashboard</a>
<script>
document.addEventListener('DOMContentLoaded', () => {
    const roleSelectors = document.querySelectorAll('.change-role');
    const deleteButtons = document.querySelectorAll('.delete-user');

    // Cambio de rol (igual que antes)
    roleSelectors.forEach(selector => {
        selector.addEventListener('change', (event) => {
            const userId = event.target.getAttribute('data-user-id');
            const newRole = event.target.value;

            fetch(`/admin/users/${userId}/change_role`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `role=${newRole}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.message) {
                    showToast(data.message, 'bg-success');
                } else if (data.error) {
                    showToast(`Error: ${data.error}`, 'bg-danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An unexpected error occurred.', 'bg-danger');
            });
        });
    });

    // Eliminar usuario
    deleteButtons.forEach(btn => {
        btn.addEventListener('click', (e) => {
            e.preventDefault(); // Evitamos la acción por defecto

            const userId = btn.getAttribute('data-user-id');

            fetch(`/admin/users/delete/${userId}`, {
                method: 'POST'
            })
            .then(response => {
                if (response.redirected) {
                    // Si el servidor redirecciona, recargamos la página
                    window.location.href = response.url;
                    return;
                }
                return response.json();
            })
            .then(data => {
                if (data.message) {
                    // Mostramos toast de éxito
                    showToast(data.message, 'bg-success');
                    // Opcionalmente, remover la fila de la tabla sin recargar
                    const row = btn.closest('tr');
                    row.remove();
                } else if (data.error) {
                    showToast(`Error: ${data.error}`, 'bg-danger');
                }
            })
            .catch(err => {
                console.error('Error:', err);
                showToast('An unexpected error occurred.', 'bg-danger');
            });
        });
    });
});
</script>

{% endblock %}


