{% extends "base.html" %}

{% block title %}{{ page_title }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1>User Management</h1>
            <p>Manage user accounts and permissions.</p>
            
            <!-- User List -->
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5>Users</h5>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createUserModal">
                        <i class="fas fa-plus"></i> Create User
                    </button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Username</th>
                                    <th>Email</th>
                                    <th>Role</th>
                                    <th>Last Login</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="users-table-body">
                                <!-- User rows will be populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Create User Modal -->
<div class="modal fade" id="createUserModal" tabindex="-1" aria-labelledby="createUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createUserModalLabel">Create New User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="create-user-form">
                    <div class="mb-3">
                        <label for="username" class="form-label">Username</label>
                        <input type="text" class="form-control" id="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">Email</label>
                        <input type="email" class="form-control" id="email" required>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">Password</label>
                        <input type="password" class="form-control" id="password" required>
                    </div>
                    <div class="mb-3">
                        <label for="confirm-password" class="form-label">Confirm Password</label>
                        <input type="password" class="form-control" id="confirm-password" required>
                    </div>
                    <div class="mb-3">
                        <label for="user-role" class="form-label">User Role</label>
                        <select class="form-select" id="user-role" required>
                            <option value="normal">Normal User</option>
                            <option value="cashier">Cashier</option>
                            <option value="admin">Administrator</option>
                        </select>
                        <div class="form-text">
                            <strong>Normal User:</strong> Full dashboard access<br>
                            <strong>Cashier:</strong> Limited access to video/overlay controls only<br>
                            <strong>Administrator:</strong> Full system access including user management
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="create-user-btn">Create User</button>
            </div>
        </div>
    </div>
</div>

<script>
    // Load users on page load
    function loadUsers() {
        fetch('/api/users')
            .then(response => response.json())
            .then(data => {
                const tbody = document.getElementById('users-table-body');
                tbody.innerHTML = '';
                
                if (data.error) {
                    tbody.innerHTML = '<tr><td colspan="5" class="text-center text-danger">Error loading users: ' + data.error + '</td></tr>';
                    return;
                }
                
                const users = data.users || [];
                users.forEach(user => {
                    // Determine role display
                    let roleDisplay = 'Normal User';
                    let roleBadgeClass = 'bg-primary';
                    
                    if (user.role) {
                        if (user.role === 'admin') {
                            roleDisplay = 'Administrator';
                            roleBadgeClass = 'bg-danger';
                        } else if (user.role === 'cashier') {
                            roleDisplay = 'Cashier';
                            roleBadgeClass = 'bg-info';
                        } else {
                            roleDisplay = 'Normal User';
                            roleBadgeClass = 'bg-primary';
                        }
                    } else if (user.is_admin) {
                        // Backward compatibility
                        roleDisplay = 'Administrator';
                        roleBadgeClass = 'bg-danger';
                    }
                    
                    const row = document.createElement('tr');
                    
                    // Disable delete for the default admin user
                    const isDefaultAdmin = user.username === 'admin';
                    const deleteButton = isDefaultAdmin
                        ? `<button class="btn btn-sm btn-danger" disabled title="Cannot delete default admin user">Delete</button>`
                        : `<button class="btn btn-sm btn-danger delete-user" data-id="${user.id}">Delete</button>`;
                    
                    row.innerHTML = `
                        <td>${user.username}</td>
                        <td>${user.email}</td>
                        <td><span class="badge ${roleBadgeClass}">${roleDisplay}</span></td>
                        <td>${user.last_login || 'Never'}</td>
                        <td>
                            <button class="btn btn-sm btn-primary edit-user" data-id="${user.id}" data-role="${user.role || (user.is_admin ? 'admin' : 'normal')}">Edit</button>
                            ${deleteButton}
                        </td>
                    `;
                    tbody.appendChild(row);
                });
                
                // Add event listeners to action buttons
                document.querySelectorAll('.edit-user').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const userId = this.getAttribute('data-id');
                        editUser(userId);
                    });
                });
                
                document.querySelectorAll('.delete-user').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const userId = this.getAttribute('data-id');
                        deleteUser(userId);
                    });
                });
            })
            .catch(error => {
                console.error('Error loading users:', error);
            });
    }
    
    // Edit user
    function editUser(userId) {
        // Get user data first
        const editButton = document.querySelector(`[data-id="${userId}"].edit-user`);
        const userRow = editButton.closest('tr');
        const cells = userRow.querySelectorAll('td');
        const currentUsername = cells[0].textContent;
        const currentEmail = cells[1].textContent;
        const currentRole = editButton.getAttribute('data-role') || 'normal';
        
        // Create edit modal dynamically
        const editModal = `
            <div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="editUserModalLabel">Edit User</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="edit-user-form">
                                <div class="mb-3">
                                    <label for="edit-username" class="form-label">Username</label>
                                    <input type="text" class="form-control" id="edit-username" value="${currentUsername}" required>
                                </div>
                                <div class="mb-3">
                                    <label for="edit-email" class="form-label">Email</label>
                                    <input type="email" class="form-control" id="edit-email" value="${currentEmail}" required>
                                </div>
                                <div class="mb-3">
                                    <label for="edit-password" class="form-label">New Password (leave empty to keep current)</label>
                                    <input type="password" class="form-control" id="edit-password">
                                </div>
                                <div class="mb-3">
                                    <label for="edit-user-role" class="form-label">User Role</label>
                                    <select class="form-select" id="edit-user-role" required>
                                        <option value="normal" ${currentRole === 'normal' ? 'selected' : ''}>Normal User</option>
                                        <option value="cashier" ${currentRole === 'cashier' ? 'selected' : ''}>Cashier</option>
                                        <option value="admin" ${currentRole === 'admin' ? 'selected' : ''}>Administrator</option>
                                    </select>
                                    <div class="form-text">
                                        <strong>Normal User:</strong> Full dashboard access<br>
                                        <strong>Cashier:</strong> Limited access to video/overlay controls only<br>
                                        <strong>Administrator:</strong> Full system access including user management
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-primary" id="save-user-btn">Save Changes</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // Remove existing edit modal if present
        const existingModal = document.getElementById('editUserModal');
        if (existingModal) {
            existingModal.remove();
        }
        
        // Add modal to page
        document.body.insertAdjacentHTML('beforeend', editModal);
        
        // Show modal
        const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
        modal.show();
        
        // Add save button event listener
        document.getElementById('save-user-btn').addEventListener('click', function() {
            const username = document.getElementById('edit-username').value;
            const email = document.getElementById('edit-email').value;
            const password = document.getElementById('edit-password').value;
            const role = document.getElementById('edit-user-role').value;
            
            if (!username || !email || !role) {
                alert('Username, email and role are required');
                return;
            }
            
            const updateData = {
                username: username,
                email: email,
                role: role,
                is_admin: role === 'admin' // For backward compatibility
            };
            
            // Only include password if it's provided
            if (password) {
                updateData.password = password;
            }
            
            // Update user via API
            fetch(`/api/users/${userId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(updateData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Close modal
                    modal.hide();
                    
                    // Refresh user list
                    loadUsers();
                } else {
                    alert('Failed to update user: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error updating user:', error);
                alert('Error updating user: ' + error.message);
            });
        });
        
        // Clean up modal when closed
        document.getElementById('editUserModal').addEventListener('hidden.bs.modal', function () {
            this.remove();
        });
    }
    
    // Delete user
    function deleteUser(userId) {
        if (confirm('Are you sure you want to delete this user?')) {
            fetch(`/api/users/${userId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadUsers();
                } else {
                    alert('Failed to delete user: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error deleting user:', error);
                alert('Error deleting user: ' + error.message);
            });
        }
    }
    
    // Create user
    document.getElementById('create-user-btn').addEventListener('click', function() {
        const username = document.getElementById('username').value;
        const email = document.getElementById('email').value;
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirm-password').value;
        const role = document.getElementById('user-role').value;
        
        if (!username || !email || !password || !confirmPassword || !role) {
            alert('All fields are required');
            return;
        }
        
        if (password !== confirmPassword) {
            alert('Passwords do not match');
            return;
        }
        
        // Create user via API
        fetch('/api/users', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: username,
                email: email,
                password: password,
                role: role,
                is_admin: role === 'admin' // For backward compatibility
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Reset form
                document.getElementById('create-user-form').reset();
                
                // Close modal
                const modal = bootstrap.Modal.getInstance(document.getElementById('createUserModal'));
                modal.hide();
                
                // Refresh user list
                loadUsers();
            } else {
                alert('Failed to create user: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error creating user:', error);
            alert('Error creating user: ' + error.message);
        });
    });
    
    // Load users when page loads
    document.addEventListener('DOMContentLoaded', function() {
        loadUsers();
    });
</script>
{% endblock %}
