<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management - Fixture Manager</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #007bff;
            color: white;
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo {
            font-size: 1.5rem;
            font-weight: bold;
        }
        .nav {
            display: flex;
            gap: 1rem;
        }
        .nav a {
            color: white;
            text-decoration: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            transition: background-color 0.3s;
        }
        .nav a:hover {
            background-color: rgba(255,255,255,0.1);
        }
        .container { 
            max-width: 1200px; 
            margin: 2rem auto; 
            padding: 0 2rem; 
            background: white; 
            padding: 2rem; 
            border-radius: 8px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.1); 
        }
        .btn { 
            padding: 8px 16px; 
            background-color: #007bff; 
            color: white; 
            text-decoration: none; 
            border-radius: 4px; 
            display: inline-block; 
            margin: 0.5rem 0; 
            border: none;
            cursor: pointer;
            font-size: 0.9rem;
        }
        .btn:hover { background-color: #0056b3; }
        .btn-success { background-color: #28a745; }
        .btn-success:hover { background-color: #218838; }
        .btn-danger { background-color: #dc3545; }
        .btn-danger:hover { background-color: #c82333; }
        .btn-warning { background-color: #ffc107; color: #212529; }
        .btn-warning:hover { background-color: #e0a800; }
        .btn-secondary { background-color: #6c757d; }
        .btn-secondary:hover { background-color: #5a6268; }
        .btn-sm { padding: 4px 8px; font-size: 0.8rem; margin: 0 2px; }
        
        .controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            flex-wrap: wrap;
            gap: 1rem;
        }
        .search-filters {
            display: flex;
            gap: 1rem;
            align-items: center;
            flex-wrap: wrap;
        }
        .search-filters input, .search-filters select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        table { 
            width: 100%; 
            border-collapse: collapse; 
            margin-top: 1rem; 
        }
        th, td { 
            padding: 12px; 
            text-align: left; 
            border-bottom: 1px solid #ddd; 
        }
        th { 
            background-color: #f8f9fa; 
            font-weight: bold; 
            position: sticky;
            top: 0;
        }
        .status-active { color: #28a745; font-weight: bold; }
        .status-inactive { color: #dc3545; font-weight: bold; }
        .admin-badge { 
            background-color: #007bff; 
            color: white; 
            padding: 2px 6px; 
            border-radius: 3px; 
            font-size: 0.8rem; 
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 2rem;
            border-radius: 8px;
            width: 90%;
            max-width: 500px;
            max-height: 80vh;
            overflow-y: auto;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #ddd;
        }
        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover { color: black; }
        
        .form-group {
            margin-bottom: 1rem;
        }
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: bold;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .form-group input[type="checkbox"] {
            width: auto;
            margin-right: 0.5rem;
        }
        .checkbox-group {
            display: flex;
            align-items: center;
            margin-top: 0.5rem;
        }
        
        .alert {
            padding: 12px;
            margin-bottom: 1rem;
            border-radius: 4px;
            display: none;
        }
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .settings-section {
            background-color: #f8f9fa;
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 2rem;
        }
        .settings-section h3 {
            margin-top: 0;
            color: #495057;
        }
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }
        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        input:checked + .slider {
            background-color: #007bff;
        }
        input:checked + .slider:before {
            transform: translateX(26px);
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 2rem;
        }
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #007bff;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="logo">🥊 Fixture Manager</div>
        <div class="nav">
            <a href="{{ url_for('main.dashboard') }}">Dashboard</a>
            <a href="{{ url_for('main.fixtures') }}">Fixtures</a>
            <a href="{{ url_for('main.uploads') }}">Uploads</a>
            <a href="{{ url_for('main.statistics') }}">Statistics</a>
            {% if current_user.is_admin %}
                <a href="{{ url_for('main.admin_panel') }}">Admin</a>
            {% endif %}
            <a href="{{ url_for('auth.logout') }}">Logout</a>
        </div>
    </div>

    <div class="container">
        <h1>User Management</h1>
        <a href="{{ url_for('main.admin_panel') }}" class="btn">← Back to Admin Panel</a>
        
        <div id="alert" class="alert"></div>
        
        <!-- Registration Settings -->
        <div class="settings-section">
            <h3>Registration Settings</h3>
            <div style="display: flex; align-items: center; gap: 1rem;">
                <label class="toggle-switch">
                    <input type="checkbox" id="registrationToggle">
                    <span class="slider"></span>
                </label>
                <span id="registrationStatus">Loading...</span>
            </div>
        </div>
        
        <!-- User Controls -->
        <div class="controls">
            <div class="search-filters">
                <input type="text" id="searchInput" placeholder="Search users..." style="width: 200px;">
                <select id="statusFilter">
                    <option value="">All Users</option>
                    <option value="active">Active Only</option>
                    <option value="inactive">Inactive Only</option>
                    <option value="admin">Admins Only</option>
                </select>
                <button class="btn" onclick="filterUsers()">Filter</button>
            </div>
            <button class="btn btn-success" onclick="showCreateUserModal()">+ Add New User</button>
        </div>
        
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>Loading users...</p>
        </div>
        
        {% if users %}
        <table id="usersTable">
            <thead>
                <tr>
                    <th>Username</th>
                    <th>Email</th>
                    <th>Status</th>
                    <th>Admin</th>
                    <th>Created</th>
                    <th>Last Login</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                {% for user in users %}
                <tr data-user-id="{{ user.id }}">
                    <td>{{ user.username }}</td>
                    <td>{{ user.email }}</td>
                    <td class="{{ 'status-active' if user.is_active else 'status-inactive' }}">
                        {{ 'Active' if user.is_active else 'Inactive' }}
                    </td>
                    <td>
                        {% if user.is_admin %}
                            <span class="admin-badge">Admin</span>
                        {% else %}
                            User
                        {% endif %}
                    </td>
                    <td>{{ user.created_at.strftime('%Y-%m-%d') if user.created_at else 'N/A' }}</td>
                    <td>{{ user.last_login.strftime('%Y-%m-%d %H:%M') if user.last_login else 'Never' }}</td>
                    <td>
                        <button class="btn btn-sm" onclick="editUser({{ user.id }})">Edit</button>
                        <button class="btn btn-warning btn-sm" onclick="resetPassword({{ user.id }})">Reset Password</button>
                        {% if user.is_active %}
                            <button class="btn btn-secondary btn-sm" onclick="toggleUserStatus({{ user.id }}, false)">Suspend</button>
                        {% else %}
                            <button class="btn btn-success btn-sm" onclick="toggleUserStatus({{ user.id }}, true)">Activate</button>
                        {% endif %}
                        {% if user.id != current_user.id %}
                            <button class="btn btn-danger btn-sm" onclick="deleteUser({{ user.id }})">Delete</button>
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        {% else %}
        <p>No users found.</p>
        {% endif %}
    </div>

    <!-- Create User Modal -->
    <div id="createUserModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Create New User</h2>
                <span class="close" onclick="closeModal('createUserModal')">&times;</span>
            </div>
            <form id="createUserForm">
                <div class="form-group">
                    <label for="createUsername">Username:</label>
                    <input type="text" id="createUsername" name="username" required>
                </div>
                <div class="form-group">
                    <label for="createEmail">Email:</label>
                    <input type="email" id="createEmail" name="email" required>
                </div>
                <div class="form-group">
                    <label for="createPassword">Password:</label>
                    <input type="password" id="createPassword" name="password" required>
                </div>
                <div class="form-group">
                    <label for="createPassword2">Confirm Password:</label>
                    <input type="password" id="createPassword2" name="password2" required>
                </div>
                <div class="form-group">
                    <div class="checkbox-group">
                        <input type="checkbox" id="createIsActive" name="is_active" checked>
                        <label for="createIsActive">Active</label>
                    </div>
                </div>
                <div class="form-group">
                    <div class="checkbox-group">
                        <input type="checkbox" id="createIsAdmin" name="is_admin">
                        <label for="createIsAdmin">Administrator</label>
                    </div>
                </div>
                <div style="text-align: right; margin-top: 2rem;">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('createUserModal')">Cancel</button>
                    <button type="submit" class="btn btn-success">Create User</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div id="editUserModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Edit User</h2>
                <span class="close" onclick="closeModal('editUserModal')">&times;</span>
            </div>
            <form id="editUserForm">
                <input type="hidden" id="editUserId" name="user_id">
                <div class="form-group">
                    <label for="editUsername">Username:</label>
                    <input type="text" id="editUsername" name="username" required>
                </div>
                <div class="form-group">
                    <label for="editEmail">Email:</label>
                    <input type="email" id="editEmail" name="email" required>
                </div>
                <div class="form-group">
                    <div class="checkbox-group">
                        <input type="checkbox" id="editIsActive" name="is_active">
                        <label for="editIsActive">Active</label>
                    </div>
                </div>
                <div class="form-group">
                    <div class="checkbox-group">
                        <input type="checkbox" id="editIsAdmin" name="is_admin">
                        <label for="editIsAdmin">Administrator</label>
                    </div>
                </div>
                <div style="text-align: right; margin-top: 2rem;">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('editUserModal')">Cancel</button>
                    <button type="submit" class="btn btn-success">Update User</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Reset Password Modal -->
    <div id="resetPasswordModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Reset User Password</h2>
                <span class="close" onclick="closeModal('resetPasswordModal')">&times;</span>
            </div>
            <form id="resetPasswordForm">
                <input type="hidden" id="resetUserId" name="user_id">
                <div class="form-group">
                    <label for="newPassword">New Password:</label>
                    <input type="password" id="newPassword" name="new_password" required>
                </div>
                <div class="form-group">
                    <label for="newPassword2">Confirm New Password:</label>
                    <input type="password" id="newPassword2" name="new_password2" required>
                </div>
                <div style="text-align: right; margin-top: 2rem;">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('resetPasswordModal')">Cancel</button>
                    <button type="submit" class="btn btn-warning">Reset Password</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Load registration settings on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadRegistrationSettings();
        });

        // Registration toggle functionality
        function loadRegistrationSettings() {
            fetch('/admin/settings/registration')
                .then(response => response.json())
                .then(data => {
                    const toggle = document.getElementById('registrationToggle');
                    const status = document.getElementById('registrationStatus');
                    
                    toggle.checked = data.registration_enabled;
                    status.textContent = data.registration_enabled ? 'Registration Enabled' : 'Registration Disabled';
                    
                    toggle.addEventListener('change', function() {
                        toggleRegistration(this.checked);
                    });
                })
                .catch(error => {
                    console.error('Error loading registration settings:', error);
                    document.getElementById('registrationStatus').textContent = 'Error loading settings';
                });
        }

        function toggleRegistration(enabled) {
            const data = { registration_enabled: enabled };
            
            fetch('/admin/settings/registration', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showAlert(data.error, 'error');
                } else {
                    const status = document.getElementById('registrationStatus');
                    status.textContent = data.registration_enabled ? 'Registration Enabled' : 'Registration Disabled';
                    showAlert(data.message, 'success');
                }
            })
            .catch(error => {
                console.error('Error updating registration settings:', error);
                showAlert('Failed to update registration settings', 'error');
            });
        }

        // Modal functions
        function showCreateUserModal() {
            document.getElementById('createUserModal').style.display = 'block';
        }

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // User management functions
        function editUser(userId) {
            // Get user data from table row
            const row = document.querySelector(`tr[data-user-id="${userId}"]`);
            const cells = row.querySelectorAll('td');
            
            document.getElementById('editUserId').value = userId;
            document.getElementById('editUsername').value = cells[0].textContent;
            document.getElementById('editEmail').value = cells[1].textContent;
            document.getElementById('editIsActive').checked = cells[2].textContent.trim() === 'Active';
            document.getElementById('editIsAdmin').checked = cells[3].textContent.includes('Admin');
            
            document.getElementById('editUserModal').style.display = 'block';
        }

        function resetPassword(userId) {
            document.getElementById('resetUserId').value = userId;
            document.getElementById('resetPasswordModal').style.display = 'block';
        }

        function toggleUserStatus(userId, activate) {
            const action = activate ? 'activate' : 'suspend';
            if (confirm(`Are you sure you want to ${action} this user?`)) {
                const data = { is_active: activate };
                
                fetch(`/admin/users/${userId}/edit`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        showAlert(data.error, 'error');
                    } else {
                        showAlert(data.message, 'success');
                        setTimeout(() => location.reload(), 1500);
                    }
                })
                .catch(error => {
                    console.error('Error updating user status:', error);
                    showAlert('Failed to update user status', 'error');
                });
            }
        }

        function deleteUser(userId) {
            if (confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
                fetch(`/admin/users/${userId}/delete`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        showAlert(data.error, 'error');
                    } else {
                        showAlert(data.message, 'success');
                        setTimeout(() => location.reload(), 1500);
                    }
                })
                .catch(error => {
                    console.error('Error deleting user:', error);
                    showAlert('Failed to delete user', 'error');
                });
            }
        }

        // Form submissions
        document.getElementById('createUserForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = {
                username: formData.get('username'),
                email: formData.get('email'),
                password: formData.get('password'),
                is_active: formData.get('is_active') === 'on',
                is_admin: formData.get('is_admin') === 'on'
            };
            
            // Validate password confirmation
            if (data.password !== formData.get('password2')) {
                showAlert('Passwords do not match', 'error');
                return;
            }
            
            fetch('/admin/users/create', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showAlert(data.error, 'error');
                } else {
                    showAlert(data.message, 'success');
                    closeModal('createUserModal');
                    setTimeout(() => location.reload(), 1500);
                }
            })
            .catch(error => {
                console.error('Error creating user:', error);
                showAlert('Failed to create user', 'error');
            });
        });

        document.getElementById('editUserForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const userId = formData.get('user_id');
            const data = {
                username: formData.get('username'),
                email: formData.get('email'),
                is_active: formData.get('is_active') === 'on',
                is_admin: formData.get('is_admin') === 'on'
            };
            
            fetch(`/admin/users/${userId}/edit`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showAlert(data.error, 'error');
                } else {
                    showAlert(data.message, 'success');
                    closeModal('editUserModal');
                    setTimeout(() => location.reload(), 1500);
                }
            })
            .catch(error => {
                console.error('Error updating user:', error);
                showAlert('Failed to update user', 'error');
            });
        });

        document.getElementById('resetPasswordForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const userId = formData.get('user_id');
            const newPassword = formData.get('new_password');
            const newPassword2 = formData.get('new_password2');
            
            // Validate password confirmation
            if (newPassword !== newPassword2) {
                showAlert('Passwords do not match', 'error');
                return;
            }
            
            const data = { new_password: newPassword };
            
            fetch(`/admin/users/${userId}/reset-password`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showAlert(data.error, 'error');
                } else {
                    showAlert(data.message, 'success');
                    closeModal('resetPasswordModal');
                }
            })
            .catch(error => {
                console.error('Error resetting password:', error);
                showAlert('Failed to reset password', 'error');
            });
        });

        // Utility functions
        function showAlert(message, type) {
            const alert = document.getElementById('alert');
            alert.textContent = message;
            alert.className = `alert alert-${type}`;
            alert.style.display = 'block';
            
            setTimeout(() => {
                alert.style.display = 'none';
            }, 5000);
        }

        function filterUsers() {
            const search = document.getElementById('searchInput').value.toLowerCase();
            const status = document.getElementById('statusFilter').value;
            const rows = document.querySelectorAll('#usersTable tbody tr');
            
            rows.forEach(row => {
                const username = row.cells[0].textContent.toLowerCase();
                const email = row.cells[1].textContent.toLowerCase();
                const userStatus = row.cells[2].textContent.trim().toLowerCase();
                const isAdmin = row.cells[3].textContent.includes('Admin');
                
                let showRow = true;
                
                // Search filter
                if (search && !username.includes(search) && !email.includes(search)) {
                    showRow = false;
                }
                
                // Status filter
                if (status) {
                    if (status === 'active' && userStatus !== 'active') showRow = false;
                    if (status === 'inactive' && userStatus !== 'inactive') showRow = false;
                    if (status === 'admin' && !isAdmin) showRow = false;
                }
                
                row.style.display = showRow ? '' : 'none';
            });
        }

        // Close modals when clicking outside
        window.onclick = function(event) {
            const modals = document.querySelectorAll('.modal');
            modals.forEach(modal => {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });
        }
    </script>
</body>
</html>