<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Manager - CGW Product Finder</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
        }

        .header {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            margin-bottom: 30px;
            text-align: center;
        }

        .header h1 {
            color: #333;
            margin-bottom: 10px;
        }

        .header p {
            color: #666;
        }

        .card {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            margin-bottom: 30px;
        }

        .card h2 {
            color: #333;
            margin-bottom: 20px;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 600;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }

        .location-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        .location-table th {
            background: #667eea;
            color: white;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            border: 1px solid #5568d3;
        }

        .location-table th.checkbox-header {
            text-align: center;
            width: 100px;
            cursor: pointer;
            user-select: none;
        }

        .location-table th.checkbox-header:hover {
            background: #5568d3;
        }

        .location-table td {
            padding: 12px;
            border: 1px solid #e0e0e0;
            background: white;
        }

        .location-table td.checkbox-cell {
            text-align: center;
        }

        .location-table tr:hover td {
            background: #f7fafc;
        }

        .location-table input[type="checkbox"],
        .location-table input[type="radio"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .location-table label {
            cursor: pointer;
            display: flex;
            align-items: center;
        }

        .location-name {
            font-weight: 500;
            color: #333;
        }

        .tooltip-header {
            position: relative;
            display: inline-block;
            cursor: help;
        }

        .tooltip-header .tooltip-text {
            visibility: hidden;
            width: 200px;
            background-color: #333;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 8px;
            position: absolute;
            z-index: 1000;
            bottom: 125%;
            left: 50%;
            margin-left: -100px;
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 13px;
            font-weight: normal;
        }

        .tooltip-header .tooltip-text::after {
            content: "";
            position: absolute;
            top: 100%;
            left: 50%;
            margin-left: -5px;
            border-width: 5px;
            border-style: solid;
            border-color: #333 transparent transparent transparent;
        }

        .tooltip-header:hover .tooltip-text {
            visibility: visible;
            opacity: 1;
        }

        .btn {
            padding: 12px 30px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background: #5568d3;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-success {
            background: #48bb78;
            color: white;
        }

        .btn-success:hover {
            background: #38a169;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(72, 187, 120, 0.4);
        }

        .btn-danger {
            background: #f56565;
            color: white;
            margin-left: 10px;
        }

        .btn-danger:hover {
            background: #e53e3e;
        }

        .btn-warning {
            background: #ed8936;
            color: white;
        }

        .btn-warning:hover {
            background: #dd6b20;
        }

        .user-list {
            margin-top: 20px;
        }

        .user-item {
            background: #f7fafc;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-left: 4px solid #667eea;
        }

        .user-item.inactive {
            opacity: 0.6;
            border-left-color: #cbd5e0;
        }

        .user-actions {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .active-toggle {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #666;
        }

        .active-toggle input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .active-label {
            font-weight: 500;
        }

        .active-label.active {
            color: #48bb78;
        }

        .active-label.inactive {
            color: #f56565;
        }

        .user-info {
            flex: 1;
        }

        .user-info strong {
            color: #333;
            display: block;
            margin-bottom: 5px;
        }

        .user-info span {
            color: #666;
            font-size: 14px;
        }

        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            display: none;
        }

        .alert.show {
            display: block;
        }

        .alert-success {
            background: #c6f6d5;
            color: #22543d;
            border-left: 4px solid #48bb78;
        }

        .alert-error {
            background: #fed7d7;
            color: #742a2a;
            border-left: 4px solid #f56565;
        }

        .button-group {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }

        .stats {
            display: flex;
            justify-content: space-around;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 2px solid #e0e0e0;
        }

        .stat-item {
            text-align: center;
        }

        .stat-number {
            font-size: 32px;
            font-weight: bold;
            color: #667eea;
        }

        .stat-label {
            color: #666;
            font-size: 14px;
        }

        .back-link {
            display: inline-block;
            margin-top: 20px;
            color: white;
            text-decoration: none;
            padding: 10px 20px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 5px;
            transition: background 0.3s;
        }

        .back-link:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            justify-content: center;
            align-items: center;
        }

        .modal.show {
            display: flex;
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            width: 90%;
            max-width: 500px;
            position: relative;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e0e0e0;
        }

        .modal-header h2 {
            margin: 0;
            color: #333;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 28px;
            color: #999;
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .close-btn:hover {
            color: #f56565;
        }

        .modal-body {
            margin-bottom: 20px;
        }

        .security-note {
            background: #fef5e7;
            border-left: 4px solid #ed8936;
            padding: 12px;
            margin-bottom: 20px;
            border-radius: 4px;
            font-size: 14px;
            color: #744210;
        }

        .security-note strong {
            display: block;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔐 User Manager</h1>
            <p>Create and manage user accounts with secure password encoding</p>
        </div>

        <div class="alert alert-success" id="successAlert"></div>
        <div class="alert alert-error" id="errorAlert"></div>

        <div class="card">
            <h2>Add New User</h2>
            <form id="userForm">
                <div class="form-group">
                    <label for="username">Username *</label>
                    <input type="text" id="username" name="username" required 
                           placeholder="Enter username (e.g., john_doe)">
                </div>

                <div class="form-group">
                    <label for="password">Password *</label>
                    <input type="password" id="password" name="password" required 
                           placeholder="Enter a secure password" minlength="6">
                </div>

                <div class="form-group">
                    <label>Location Configuration</label>
                    <table class="location-table">
                        <thead>
                            <tr>
                                <th>Default Location *</th>
                                <th class="checkbox-header">
                                    <label class="tooltip-header" style="display: flex; align-items: center; justify-content: center; cursor: pointer; margin: 0;">
                                        <input type="checkbox" id="headerAccessible" onchange="toggleAllCheckboxes('accessible')" style="margin: 0;">
                                        <span class="tooltip-text">Can access location</span>
                                    </label>
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>
                                    <label>
                                        <input type="radio" name="defaultLocation" value="LINDS" required style="margin-right: 8px;">
                                        <span class="location-name">Lindsborg</span>
                                    </label>
                                </td>
                                <td class="checkbox-cell">
                                    <input type="checkbox" class="accessible-checkbox" data-location="LINDS" onchange="updateHeaderCheckbox('accessible')">
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <label>
                                        <input type="radio" name="defaultLocation" value="IOLA" required style="margin-right: 8px;">
                                        <span class="location-name">Iola</span>
                                    </label>
                                </td>
                                <td class="checkbox-cell">
                                    <input type="checkbox" class="accessible-checkbox" data-location="IOLA" onchange="updateHeaderCheckbox('accessible')">
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <label>
                                        <input type="radio" name="defaultLocation" value="KC" required style="margin-right: 8px;">
                                        <span class="location-name">KC</span>
                                    </label>
                                </td>
                                <td class="checkbox-cell">
                                    <input type="checkbox" class="accessible-checkbox" data-location="KC" onchange="updateHeaderCheckbox('accessible')">
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <label>
                                        <input type="radio" name="defaultLocation" value="BMD" required style="margin-right: 8px;">
                                        <span class="location-name">BMD</span>
                                    </label>
                                </td>
                                <td class="checkbox-cell">
                                    <input type="checkbox" class="accessible-checkbox" data-location="BMD" onchange="updateHeaderCheckbox('accessible')">
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <button type="submit" class="btn btn-primary">Add User</button>
            </form>

            <div class="stats">
                <div class="stat-item">
                    <div class="stat-number" id="userCount">0</div>
                    <div class="stat-label">Total Users</div>
                </div>
            </div>
        </div>

        <div class="card">
            <h2>User List</h2>
            <div class="user-list" id="userList">
                <p style="color: #666; text-align: center;">No users added yet.</p>
            </div>

            <div class="button-group">
                <button class="btn btn-success" id="downloadBtn" onclick="downloadUsers()">
                    📥 Download Users JSON
                </button>
                <button class="btn btn-danger" id="clearBtn" onclick="clearAllUsers()">
                    🗑️ Clear All Users
                </button>
            </div>
        </div>

        <a href="{{ url_for('index') }}" class="back-link">← Back to Product Finder</a>
    </div>

    <!-- Change Password Modal -->
    <div id="changePasswordModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>🔑 Change Password</h2>
                <button class="close-btn" onclick="closePasswordModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="security-note">
                    <strong>🔒 Security Verification Required</strong>
                    You must enter your current password to change another user's password.
                </div>
                <form id="changePasswordForm">
                    <div class="form-group">
                        <label>User to Update</label>
                        <input type="text" id="targetUsername" readonly style="background: #f0f0f0;">
                    </div>
                    <div class="form-group">
                        <label for="newPassword">New Password for User *</label>
                        <input type="password" id="newPassword" required 
                               placeholder="Enter new password for this user">
                    </div>
                    <div class="form-group">
                        <label for="confirmPassword">Confirm New Password *</label>
                        <input type="password" id="confirmPassword" required 
                               placeholder="Re-enter new password">
                    </div>
                    <div class="form-group">
                        <label for="currentUserPassword">Your Password (Current User) *</label>
                        <input type="password" id="currentUserPassword" required 
                               placeholder="Enter YOUR password to verify">
                    </div>
                    <div class="button-group">
                        <button type="submit" class="btn btn-primary">
                            Change Password
                        </button>
                        <button type="button" class="btn btn-danger" onclick="closePasswordModal()">
                            Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Base URL for API calls (supports subdirectory deployments)
        const BASE_URL = '{{ base_url }}';
        
        let users = [];

        const LOCATIONS = [
            { name: 'Lindsborg', code: 'LINDS' },
            { name: 'Iola', code: 'IOLA' },
            { name: 'KC', code: 'KC' },
            { name: 'BMD', code: 'BMD' }
        ];

        // Toggle all checkboxes in a column
        function toggleAllCheckboxes(type) {
            const headerCheckbox = document.getElementById(`header${type.charAt(0).toUpperCase() + type.slice(1)}`);
            const checkboxes = document.querySelectorAll(`.${type}-checkbox`);
            
            // Get the state AFTER the checkbox was clicked (it's already toggled by the browser)
            const newState = headerCheckbox.checked;
            
            // Apply this state to all row checkboxes
            checkboxes.forEach(cb => cb.checked = newState);
            
            // Clear indeterminate state since we're setting all to the same value
            headerCheckbox.indeterminate = false;
        }

        // Update header checkbox state based on individual checkboxes
        function updateHeaderCheckbox(type) {
            const headerCheckbox = document.getElementById(`header${type.charAt(0).toUpperCase() + type.slice(1)}`);
            const checkboxes = document.querySelectorAll(`.${type}-checkbox`);
            const checkedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
            
            if (checkedCount === 0) {
                headerCheckbox.checked = false;
                headerCheckbox.indeterminate = false;
            } else if (checkedCount === checkboxes.length) {
                headerCheckbox.checked = true;
                headerCheckbox.indeterminate = false;
            } else {
                headerCheckbox.checked = false;
                headerCheckbox.indeterminate = true;
            }
        }

        // Load existing users on page load
        async function loadUsers() {
            try {
                const response = await fetch(BASE_URL + '/api/users');
                const data = await response.json();
                if (data.status === 'success') {
                    users = data.users || [];
                    renderUsers();
                }
            } catch (error) {
                console.error('Error loading users:', error);
            }
        }

        // Render users in the list
        function renderUsers() {
            const userList = document.getElementById('userList');
            const userCount = document.getElementById('userCount');
            
            userCount.textContent = users.length;

            if (users.length === 0) {
                userList.innerHTML = '<p style="color: #666; text-align: center;">No users added yet.</p>';
                return;
            }

            userList.innerHTML = users.map((user, index) => {
                // Build location info string
                let locationInfo = '';
                
                if (user.locationSettings) {
                    const defaultLoc = LOCATIONS.find(l => l.code === user.defaultLocation);
                    const defaultName = defaultLoc ? defaultLoc.name : user.defaultLocation;
                    
                    const accessible = Object.entries(user.locationSettings)
                        .filter(([code, settings]) => settings.accessible)
                        .map(([code]) => LOCATIONS.find(l => l.code === code)?.name || code);
                    
                    locationInfo = `Default: ${defaultName}`;
                    if (accessible.length > 0) locationInfo += ` | Access: ${accessible.join(', ')}`;
                } else if (user.mainLocation) {
                    // Backwards compatibility
                    const mainLoc = LOCATIONS.find(l => l.code === user.mainLocation);
                    locationInfo = `Main: ${mainLoc ? mainLoc.name : user.mainLocation}`;
                    if (user.alternateLocations && user.alternateLocations.length > 0) {
                        const altNames = user.alternateLocations.map(code => 
                            LOCATIONS.find(l => l.code === code)?.name || code
                        );
                        locationInfo += ` | Alt: ${altNames.join(', ')}`;
                    }
                } else if (user.location) {
                    // Old format
                    locationInfo = user.location;
                }
                
                const isActive = user.active !== false; // Default to active if not specified
                const activeClass = isActive ? '' : ' inactive';
                const activeStatus = isActive ? 'active' : 'inactive';
                const activeLabel = isActive ? 'Active' : 'Inactive';
                
                return `
                <div class="user-item${activeClass}">
                    <div class="user-info">
                        <strong>👤 ${user.username}</strong>
                        <span>📍 ${locationInfo}</span>
                    </div>
                    <div class="user-actions">
                        <div class="active-toggle">
                            <input type="checkbox" ${isActive ? 'checked' : ''} 
                                   onchange="toggleUserActive(${index})" 
                                   id="userActive${index}">
                            <label for="userActive${index}" class="active-label ${activeStatus}">${activeLabel}</label>
                        </div>
                        <button class="btn btn-warning" onclick="openPasswordModal(${index})" style="margin: 0 5px; padding: 8px 16px;">
                            Change Password
                        </button>
                        <button class="btn btn-danger" onclick="deleteUser(${index})" style="margin: 0; padding: 8px 16px;">
                            Delete
                        </button>
                    </div>
                </div>
            `;
            }).join('');
        }

        // Handle form submission
        document.getElementById('userForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            // Get default location (radio button)
            const defaultLocation = document.querySelector('input[name="defaultLocation"]:checked')?.value;
            
            // Get location settings
            const locationSettings = {};
            LOCATIONS.forEach(loc => {
                const accessibleCheckbox = document.querySelector(`.accessible-checkbox[data-location="${loc.code}"]`);
                
                locationSettings[loc.code] = {
                    accessible: accessibleCheckbox ? accessibleCheckbox.checked : false
                };
            });
            
            const formData = {
                username: document.getElementById('username').value,
                password: document.getElementById('password').value,
                defaultLocation: defaultLocation,
                locationSettings: locationSettings,
                active: true  // New users are active by default
            };

            try {
                const response = await fetch(BASE_URL + '/api/users', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });

                const data = await response.json();

                if (data.status === 'success') {
                    showAlert('success', `User "${formData.username}" added successfully!`);
                    users = data.users;
                    renderUsers();
                    document.getElementById('userForm').reset();
                    // Reset header checkboxes
                    document.getElementById('headerAccessible').checked = false;
                    document.getElementById('headerAccessible').indeterminate = false;
                } else {
                    showAlert('error', data.message || 'Error adding user');
                }
            } catch (error) {
                showAlert('error', 'Error connecting to server: ' + error.message);
            }
        });

        // Toggle user active status
        async function toggleUserActive(index) {
            try {
                const isActive = document.getElementById(`userActive${index}`).checked;
                
                const response = await fetch(BASE_URL + `/api/users/${index}/active`, {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ active: isActive })
                });

                const data = await response.json();

                if (data.status === 'success') {
                    users = data.users;
                    renderUsers();
                } else {
                    showAlert('error', data.message || 'Error updating user status');
                    // Revert checkbox on error
                    document.getElementById(`userActive${index}`).checked = !isActive;
                }
            } catch (error) {
                showAlert('error', 'Error connecting to server: ' + error.message);
                // Revert checkbox on error
                const checkbox = document.getElementById(`userActive${index}`);
                checkbox.checked = !checkbox.checked;
            }
        }

        // Delete a specific user
        async function deleteUser(index) {
            if (!confirm('Are you sure you want to delete this user?')) {
                return;
            }

            try {
                const response = await fetch(BASE_URL + `/api/users/${index}`, {
                    method: 'DELETE'
                });

                const data = await response.json();

                if (data.status === 'success') {
                    showAlert('success', 'User deleted successfully!');
                    users = data.users;
                    renderUsers();
                } else {
                    showAlert('error', data.message || 'Error deleting user');
                }
            } catch (error) {
                showAlert('error', 'Error connecting to server: ' + error.message);
            }
        }

        // Clear all users
        async function clearAllUsers() {
            if (!confirm('Are you sure you want to delete ALL users? This cannot be undone!')) {
                return;
            }

            try {
                const response = await fetch(BASE_URL + '/api/users/clear', {
                    method: 'DELETE'
                });

                const data = await response.json();

                if (data.status === 'success') {
                    showAlert('success', 'All users cleared successfully!');
                    users = [];
                    renderUsers();
                } else {
                    showAlert('error', data.message || 'Error clearing users');
                }
            } catch (error) {
                showAlert('error', 'Error connecting to server: ' + error.message);
            }
        }

        // Download users as JSON
        function downloadUsers() {
            if (users.length === 0) {
                showAlert('error', 'No users to download!');
                return;
            }

            window.location.href = BASE_URL + '/api/users/download';
            showAlert('success', 'Downloading users.json...');
        }

        // Password change modal functions
        let targetUserIndex = null;

        function openPasswordModal(userIndex) {
            targetUserIndex = userIndex;
            const user = users[userIndex];
            document.getElementById('targetUsername').value = user.username;
            document.getElementById('changePasswordModal').classList.add('show');
            document.getElementById('changePasswordForm').reset();
            document.getElementById('targetUsername').value = user.username;
        }

        function closePasswordModal() {
            document.getElementById('changePasswordModal').classList.remove('show');
            document.getElementById('changePasswordForm').reset();
            targetUserIndex = null;
        }

        // Handle password change form submission
        document.getElementById('changePasswordForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            const currentUserPassword = document.getElementById('currentUserPassword').value;

            // Validate passwords match
            if (newPassword !== confirmPassword) {
                showAlert('error', 'New passwords do not match!');
                return;
            }

            // Validate password length
            if (newPassword.length < 6) {
                showAlert('error', 'Password must be at least 6 characters long!');
                return;
            }

            try {
                const response = await fetch(BASE_URL + `/api/users/${targetUserIndex}/change-password`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        newPassword: newPassword,
                        currentUserPassword: currentUserPassword
                    })
                });

                const data = await response.json();

                if (data.status === 'success') {
                    showAlert('success', data.message);
                    closePasswordModal();
                } else {
                    showAlert('error', data.message || 'Error changing password');
                }
            } catch (error) {
                showAlert('error', 'Error connecting to server. Please try again.');
            }
        });

        // Close modal when clicking outside of it
        window.onclick = function(event) {
            const modal = document.getElementById('changePasswordModal');
            if (event.target === modal) {
                closePasswordModal();
            }
        };

        // Show alert messages
        function showAlert(type, message) {
            const alertId = type === 'success' ? 'successAlert' : 'errorAlert';
            const alert = document.getElementById(alertId);
            
            alert.textContent = message;
            alert.classList.add('show');

            setTimeout(() => {
                alert.classList.remove('show');
            }, 5000);
        }

        // Load users when page loads
        loadUsers();
    </script>
</body>
</html>
