/**
 * User Management (Superuser Only)
 */
class UsersManager {
    constructor() {
        this.users = [];
        this.units = [];
        this.init();
    }

    async init() {
        await this.loadUnits();
        await this.loadUsers();
        this.setupEventListeners();
    }

    async loadUnits() {
        try {
            const data = await window.rcpFetch('units/get.php');
            
            if (data.success) {
                this.units = data.units;
                this.populateUnitSelects();
            } else {
                window.showAlert('Failed to load units: ' + data.message, 'danger');
            }
        } catch (error) {
            console.error('Error loading units:', error);
            window.showAlert('Network error loading units', 'danger');
        }
    }

    async loadUsers() {
        try {
            const data = await window.rcpFetch('users/get.php');
            
            if (data.success) {
                this.users = data.users;
                this.renderUsers();
            } else {
                window.showAlert('Failed to load users: ' + data.message, 'danger');
            }
        } catch (error) {
            console.error('Error loading users:', error);
            window.showAlert('Network error loading users', 'danger');
        }
    }

    populateUnitSelects() {
        const selects = [
            document.getElementById('userUnit'),
            document.getElementById('editUnit')
        ];
        
        selects.forEach(select => {
            if (select) {
                select.innerHTML = '<option value="">Select Unit</option>' +
                    this.units.map(unit => 
                        `<option value="${unit.name}">${window.escapeHtml(unit.name)}</option>`
                    ).join('');
            }
        });
    }

    setupEventListeners() {
        // Add user form
        document.getElementById('userForm').addEventListener('submit', (e) => this.handleAddUser(e));
        
        // Edit user form
        document.getElementById('editUserForm').addEventListener('submit', (e) => this.handleEditUser(e));
    }

    async handleAddUser(e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        
        const userData = {
            full_name: formData.get('full_name'),
            email: formData.get('email'),
            username: formData.get('username'),
            password: formData.get('password'),
            role: formData.get('role'),
            status: formData.get('status'),
            unit_name: formData.get('unit_name')
        };

        const hideLoading = window.showLoading(e.submitter);

        try {
            const data = await window.rcpFetch('users/create.php', {
                method: 'POST',
                body: JSON.stringify(userData)
            });
            
            if (data.success) {
                window.showAlert('User created successfully!', 'success');
                form.reset();
                await this.loadUsers();
            } else {
                window.showAlert('Failed to create user: ' + data.message, 'danger');
            }
        } catch (error) {
            window.showAlert('Network error: ' + error.message, 'danger');
        } finally {
            hideLoading();
        }
    }

    editUser(userId) {
        const user = this.users.find(u => u.id == userId);
        if (!user) return;

        // Don't allow editing of current user's role/status
        const currentUserId = <?= $_SESSION['user_id'] ?? 0 ?>;
        const isCurrentUser = user.id == currentUserId;

        document.getElementById('editUserId').value = user.id;
        document.getElementById('editFullName').value = user.full_name || '';
        document.getElementById('editEmail').value = user.email;
        document.getElementById('editUsername').value = user.username;
        document.getElementById('editRole').value = user.role;
        document.getElementById('editStatus').value = user.status;
        document.getElementById('editUnit').value = user.unit_name || '';
        document.getElementById('editPassword').value = '';

        // Disable role/status editing for current user
        if (isCurrentUser) {
            document.getElementById('editRole').disabled = true;
            document.getElementById('editStatus').disabled = true;
        } else {
            document.getElementById('editRole').disabled = false;
            document.getElementById('editStatus').disabled = false;
        }

        const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
        modal.show();
    }

    async handleEditUser(e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        
        const userData = {
            id: parseInt(formData.get('id')),
            full_name: formData.get('full_name'),
            email: formData.get('email'),
            username: formData.get('username'),
            role: formData.get('role'),
            status: formData.get('status'),
            unit_name: formData.get('unit_name')
        };

        // Only include password if provided
        if (formData.get('password')) {
            userData.password = formData.get('password');
        }

        const hideLoading = window.showLoading(e.submitter);

        try {
            const data = await window.rcpFetch('users/update.php', {
                method: 'POST',
                body: JSON.stringify(userData)
            });
            
            if (data.success) {
                window.showAlert('User updated successfully!', 'success');
                bootstrap.Modal.getInstance(document.getElementById('editUserModal')).hide();
                await this.loadUsers();
            } else {
                window.showAlert('Failed to update user: ' + data.message, 'danger');
            }
        } catch (error) {
            window.showAlert('Network error: ' + error.message, 'danger');
        } finally {
            hideLoading();
        }
    }

    async deleteUser(userId) {
        const user = this.users.find(u => u.id == userId);
        if (!user) return;

        // Prevent deleting current user
        const currentUserId = <?= $_SESSION['user_id'] ?? 0 ?>;
        if (user.id == currentUserId) {
            window.showAlert('You cannot delete your own account!', 'danger');
            return;
        }

        if (!confirm(`Are you sure you want to delete user "${user.full_name}"? This action cannot be undone.`)) {
            return;
        }

        try {
            const data = await window.rcpFetch('users/delete.php', {
                method: 'POST',
                body: JSON.stringify({ id: userId })
            });
            
            if (data.success) {
                window.showAlert('User deleted successfully!', 'success');
                await this.loadUsers();
            } else {
                window.showAlert('Failed to delete user: ' + data.message, 'danger');
            }
        } catch (error) {
            window.showAlert('Network error: ' + error.message, 'danger');
        }
    }

    renderUsers() {
        const tbody = document.getElementById('usersTable');
        const currentUserId = <?= $_SESSION['user_id'] ?? 0 ?>;
        
        if (this.users.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="6" class="text-center text-muted py-4">
                        <i class="fas fa-users fa-2x mb-2 d-block"></i>
                        No users found. Create the first user above.
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = this.users.map(user => {
            const isCurrentUser = user.id == currentUserId;
            
            return `
                <tr data-id="${user.id}">
                    <td>
                        <strong>${window.escapeHtml(user.full_name)}</strong>
                        ${isCurrentUser ? '<span class="badge bg-primary ms-1">You</span>' : ''}
                    </td>
                    <td>${window.escapeHtml(user.email)}</td>
                    <td>
                        <span class="badge ${this.getRoleBadgeClass(user.role)}">
                            ${user.role}
                        </span>
                    </td>
                    <td>${window.escapeHtml(user.unit_name || '-')}</td>
                    <td>
                        <span class="badge ${user.status === 'active' ? 'bg-success' : 'bg-secondary'}">
                            ${user.status}
                        </span>
                    </td>
                    <td class="text-end">
                        <button class="btn btn-sm btn-outline-primary me-1" 
                                onclick="usersManager.editUser(${user.id})"
                                ${isCurrentUser ? 'disabled title="Cannot edit own account"' : 'title="Edit"'}>
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" 
                                onclick="usersManager.deleteUser(${user.id})"
                                ${isCurrentUser ? 'disabled title="Cannot delete own account"' : 'title="Delete"'}>
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        }).join('');
    }

    getRoleBadgeClass(role) {
        const classes = {
            'superuser': 'bg-danger',
            'admin': 'bg-warning',
            'user': 'bg-secondary'
        };
        return classes[role] || 'bg-secondary';
    }
}

// Initialize users manager
let usersManager;
document.addEventListener('DOMContentLoaded', () => {
    usersManager = new UsersManager();
});