<link rel="stylesheet" href="<%=resource%>/css/common.css?v=6.1.2">
<style>

    .user-list {
        width: 100%;
        border-collapse: collapse;
        margin-top: 15px;
    }
    
    .user-list th, .user-list td {
        padding: 8px;
        border: 1px solid #ddd;
        text-align: left;
    }
    

    .mode-selection {
        margin-bottom: 10px;
        margin-top: 10px;
    }
    .delete-button {
        padding: 3px 8px;
        background-color: #ff4444;
        color: white;
        border: none;
        border-radius: 3px;
        cursor: pointer;
    }

    
    /* Modal styles */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
    }
    
    .modal-content {
        background-color: white;
        margin: 15% auto;
        padding: 20px;
        border-radius: 5px;
        width: 60%;
        max-width: 600px;
    }
    
    .user-selection {
        max-height: 300px;
        overflow-y: auto;
        margin: 15px 0;
    }
    
    .user-item {
        padding: 8px;
        border-bottom: 1px solid #eee;
        display: flex;
        align-items: center;
    }
    

    
</style>

<script type="text/javascript">//<![CDATA[
    let userData = {
        users: [],
        mode: 1
    };

    let whitelistData = {
        users: []
    };
            
    let allUsers = [];
    function initData() {
        userData.list = [];
        getAppFilterUserData();
        getAllUsersData();
        getWhitelistData();
    }


    function getAllUsersData() {
        new XHR().get('<%=url('admin/network/get_all_users')%>', {flag: 2, page: 0},
            function (x, data) {
 				if (Array.isArray(data.data.list))  
                	allUsers = data.data.list;
                renderAutoUserData();
            }
        );
    }


    function getAppFilterUserData() {
        new XHR().get('<%=url('admin/network/get_app_filter_user')%>', null,
            function (x, data) {

                userData = data.data;
				if (!Array.isArray(userData.list))                                  
                	userData.list=[]   
                renderUserData();
                render_mode_description(userData.mode);
            }
        );
    }


    function renderUserData() {
        const table = document.getElementById('user_table');
        const rows = table.querySelectorAll('.tr:not(.table-titles)');
        rows.forEach(row => row.remove());
        

        const modeRadios = document.querySelectorAll('input[name="mode"]');

        console.log("userData.mode = " + userData.mode);
        modeRadios.forEach(radio => {
            console.log("radio.value = " + radio.value);
            radio.checked = parseInt(radio.value) === userData.mode;
        });
        if (userData.mode === 1) {
            document.getElementById('user_table').style.display = 'table';
            document.getElementById('auto_user_section').style.display = 'none';
            document.getElementById('whitelist_section').style.display = 'none';
        } else {
            document.getElementById('user_table').style.display = 'none';
            document.getElementById('auto_user_section').style.display = 'block';
            document.getElementById('whitelist_section').style.display = 'block';
        }

        // Hide add button and actions column header in manual mode
        const manualAddButton = document.querySelector('.cbi-section-create:last-child .cbi-button-add');
        const whitelistAddButton = document.querySelector('#whitelist_section .cbi-button-add');
        const actionsHeader = document.querySelector('.table-titles .th:last-child');
        
        if (manualAddButton) {
            manualAddButton.style.display = userData.mode === 1 ? 'inline-block' : 'none';
        }
        if (whitelistAddButton) {
            whitelistAddButton.style.display = userData.mode === 0 ? 'inline-block' : 'none';
        }
        if (actionsHeader) {
            actionsHeader.style.display = userData.mode === 1 ? '' : 'none';
        }
        
        const displayList = userData.mode === 1 ? userData.list : allUsers;
        
        displayList.forEach((user, index) => {
            const hostname = user.hostname || '--';
            const nickname = user.nickname || '--';
            const row = document.createElement('div');
            row.className = 'tr';
            row.innerHTML = `
                <div class="td">${user.mac}</div>
                <div class="td">${hostname}</div>
                <div class="td">${nickname}</div>
                ${userData.mode === 1 ? `<div class="td"><button type="button" class="delete-button" onclick="removeUser(${index})"><%:Delete%></button></div>` : ''}
            `;
            table.appendChild(row);
        });
    }


    function renderAutoUserData() {
        const table = document.getElementById('auto_user_table');
 
        const rows = table.querySelectorAll('.tr:not(.table-titles)');
        rows.forEach(row => row.remove());
        
 
        const displayList = allUsers.filter(user => user.is_whitelist !== 1);
        
        if (displayList.length === 0) {
      
            document.getElementById('no_users_message').style.display = 'block';
        } else {
      
            document.getElementById('no_users_message').style.display = 'none';
            
      
            displayList.forEach((user, index) => {
                const hostname = user.hostname || '--';
                const nickname = user.nickname || '--';
                
                const row = document.createElement('div');
                row.className = 'tr';
                row.innerHTML = `
                    <div class="td">${user.mac}</div>
                    <div class="td">${hostname}</div>
                    <div class="td">${nickname}</div>
                                    <div class="td">
                    <button type="button" class="cbi-button cbi-button-add" onclick="addUserToWhitelist('${user.mac}')"><%:Add to Whitelist%></button>
                </div>
                `;
                table.appendChild(row);
            });
        }
    }

    function addUserToWhitelist(mac) {
        const data = {
            mac_list: [mac]
        };
        const data_str = JSON.stringify(data);
        
        new XHR().post('<%=url('admin/network/add_whitelist_user')%>', 
            { data: data_str },
            function(x, data) {
                setTimeout(() => {
                    getWhitelistData();
                    getAllUsersData(); 
                    renderAutoUserData(); 
                }, 500); 
                showSuccessMessage('<%:Add to whitelist successful%>');
            }
        );
    }

    function showSuccessMessage(message = '<%:Settings saved successfully%>') {
        const modal = document.getElementById('modal');
        const messageElement = modal.querySelector('p');
        messageElement.textContent = message;
        modal.style.display = 'flex';
        setTimeout(() => {
            modal.style.display = 'none';
        }, 1000);
    }

    function removeUser(index) {
        const userToRemove = userData.list[index];
        new XHR().post('<%=url('admin/network/del_app_filter_user')%>', 
            { mac: userToRemove.mac },
            function(x, data) {
                getAppFilterUserData();
                showSuccessMessage('<%:Delete successful%>');
            }
        );
    }
    

    function showUserModal() {
        console.log("showUserModal");
        const modal = document.getElementById('userModal');
        modal.style.display = 'flex';
        
        const userList = document.getElementById('userList');
        userList.innerHTML = '';

        allUsers.forEach(user => {
            const userElement = document.createElement('div');
            userElement.style.padding = '8px';
            userElement.style.borderBottom = '1px solid #eee';
            
            // Determine the display name
            const displayName = user.nickname || user.hostname || '';
            
            userElement.innerHTML = `
                <label style="display: flex; align-items: center;">
                    <input type="checkbox" value="${user.mac}" style="margin-right: 8px;">
                    <span>${user.mac}</span>
                    <span style="color: #666; margin-left: 8px;">${displayName ? `(${displayName})` : ''}</span>
                </label>
            `;
            userList.appendChild(userElement);
        });
    }
    
    function closeUserModal() {
        const modal = document.getElementById('userModal');
        modal.style.display = 'none';
    }

    function addSelectedUsers() {
        const userList = document.getElementById('userList');
        const checkboxes = userList.querySelectorAll('input[type="checkbox"]:checked');
        
        const selectedMacs = Array.from(checkboxes).map(checkbox => checkbox.value);
        
        var data = {
            mac_list: selectedMacs
        }
        var data_str = JSON.stringify(data);

        console.log(selectedMacs);
        new XHR().post('<%=url('admin/network/add_app_filter_user')%>', 
            { data: data_str },
            function(x, data) {
                getAppFilterUserData();
                closeUserModal();
                showSuccessMessage('<%:Add successful%>');
            }
        );
    }

    function render_mode_description(newMode) {
        const modeDescription = document.getElementById('modeDescription');
        if (newMode === 0) {
            modeDescription.textContent = '<%:In automatic mode, all newly joined terminals will be controlled, and random MAC addresses on mobile phones are also applicable%>';
        } else {
            modeDescription.textContent = '<%:In manual mode, only specified terminals are controlled%>';
        }
    }

    function switchMode(newMode) {
        userData.mode = newMode;
        renderUserData();
        render_mode_description(newMode);

        new XHR().post('<%=url('admin/network/set_app_filter_user')%>', 
        { mode: newMode },
        function(x, data) {
            console.log('Mode updated successfully');
            showSuccessMessage('<%:Mode switch successful%>');
        });
    }

    function getWhitelistData() {
        new XHR().get('<%=url('admin/network/get_whitelist_user')%>', null,
            function (x, data) {
                if (data.data && Array.isArray(data.data.list)) {
                    whitelistData.users = data.data.list;
                } else {
                    whitelistData.users = [];
                }
                renderWhitelistData();
            }
        );
    }

    function renderWhitelistData() {
        const table = document.getElementById('whitelist_table');
        if (!table) return;
        
        const rows = table.querySelectorAll('.tr:not(.table-titles)');
        rows.forEach(row => row.remove());
        
        whitelistData.users.forEach((user, index) => {
            const hostname = user.hostname || '--';
            const nickname = user.nickname || '--';
            const row = document.createElement('div');
            row.className = 'tr';
            row.innerHTML = `
                <div class="td">${user.mac}</div>
                <div class="td">${hostname}</div>
                <div class="td">${nickname}</div>
                <div class="td"><button type="button" class="delete-button" onclick="removeWhitelistUser(${index})"><%:Delete%></button></div>
            `;
            table.appendChild(row);
        });
    }

    function showWhitelistModal() {
        console.log("showWhitelistModal");
        const modal = document.getElementById('whitelistModal');
        modal.style.display = 'flex';
        
        const userList = document.getElementById('whitelistUserList');
        userList.innerHTML = '';

        allUsers.forEach(user => {
            const userElement = document.createElement('div');
            userElement.style.padding = '8px';
            userElement.style.borderBottom = '1px solid #eee';
            
            // Determine the display name
            const displayName = user.nickname || user.hostname || '';
            
            userElement.innerHTML = `
                <label style="display: flex; align-items: center;">
                    <input type="checkbox" value="${user.mac}" style="margin-right: 8px;">
                    <span>${user.mac}</span>
                    <span style="color: #666; margin-left: 8px;">${displayName ? `(${displayName})` : ''}</span>
                </label>
            `;
            userList.appendChild(userElement);
        });
    }
    
    function closeWhitelistModal() {
        const modal = document.getElementById('whitelistModal');
        modal.style.display = 'none';
    }

    function addSelectedWhitelistUsers() {
        console.log("addSelectedWhitelistUsers");
        const userList = document.getElementById('whitelistUserList');
        const checkboxes = userList.querySelectorAll('input[type="checkbox"]:checked');
        
        const selectedMacs = Array.from(checkboxes).map(checkbox => checkbox.value);
        
        var data = {
            mac_list: selectedMacs
        }
        var data_str = JSON.stringify(data);

        console.log(selectedMacs);
        new XHR().post('<%=url('admin/network/add_whitelist_user')%>', 
            { data: data_str },
            function(x, data) {
          
                setTimeout(() => {
                    getWhitelistData();
                    getAllUsersData(); 
                    renderAutoUserData(); 
                }, 500); 
                closeWhitelistModal();
                showSuccessMessage('<%:Add to whitelist successful%>');
            }
        );
    }

    function removeWhitelistUser(index) {
        const userToRemove = whitelistData.users[index];
        new XHR().post('<%=url('admin/network/del_whitelist_user')%>', 
            { mac: userToRemove.mac },
            function(x, data) {
 
                setTimeout(() => {
                    getWhitelistData();
                    getAllUsersData(); 
                    renderAutoUserData();
                }, 500);
                showSuccessMessage('<%:Remove from whitelist successful%>');
            }
        );
    }

    window.onload = initData;
//]]></script>

<div class="cbi-section cbi-tblsection">
    <div style="max-width: 1000px; margin-left: 5px;padding: 5px;">
        <div class="mode-selection">
            <input type="radio" name="mode" value="0" onclick="switchMode(0)"> <%:Automatic Mode%>
            <input type="radio" name="mode" value="1" checked onclick="switchMode(1)"> <%:Manual Mode%>
        </div>


    <div id="modeDescription" style="margin-bottom: 15px;">
        <%:In manual mode, only the following added terminals are controlled%>
    </div>
    
    <div class="table" id="user_table" style="display: none;">
        <div class="tr table-titles">
            <div class="th"><%:MAC%></div>
            <div class="th"><%:Hostname%></div>
            <div class="th"><%:Remark%></div>
            <div class="th"><%:Actions%></div>
        </div>
    </div>

    <div id="auto_user_section" style="display: none; margin-top: 20px;">
        <h3 style="margin-bottom: 15px;"><%:Effective Users%></h3>
        <div class="table" id="auto_user_table">
            <div class="tr table-titles">
                <div class="th"><%:MAC%></div>
                <div class="th"><%:Hostname%></div>
                <div class="th"><%:Remark%></div>
                <div class="th"><%:Actions%></div>
            </div>
        </div>

        <div id="no_users_message" style="display: none; text-align: center; padding: 40px 0; color: #666; font-size: 14px;">
            <%:No Users Available%>
        </div>
    </div>


    <div id="whitelist_section" style="display: none; margin-top: 20px;">
        <h3 style="margin-bottom: 15px;"><%:Whitelist Users%></h3>
        <div style="margin-bottom: 15px;"><%:Users in whitelist are not controlled%></div>
        <div class="table" id="whitelist_table">
            <div class="tr table-titles">
                <div class="th"><%:MAC%></div>
                <div class="th"><%:Hostname%></div>
                <div class="th"><%:Remark%></div>
                <div class="th"><%:Actions%></div>
            </div>
        </div>
    </div>

     <div class="cbi-section-create">
        <input type="button" class="cbi-button cbi-button-add" value="<%:Add User%>" onclick="showUserModal()" />
    </div> 

    </div>
</div>

    <div id="userModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1000; justify-content: center; align-items: center;">
        <div style="background-color: white; padding: 20px; border-radius: 5px; text-align: left; width: 400px; height: 300px; display: flex; flex-direction: column;">
            <h3 style="margin: 0 0 15px 0;"><%:Select Device%></h3>
            <div id="userList" style="flex: 1; overflow-y: auto;">
            </div>
            <div style="margin-top: 15px; text-align: right;">
                <button type="button" onclick="addSelectedUsers()" style="margin-right: 10px; padding: 5px 15px;"><%:OK%></button>
                <button type="button" onclick="closeUserModal()" style="padding: 5px 15px;"><%:Cancel%></button>
            </div>
        </div>
    </div> 

    <div id="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1000; justify-content: center; align-items: center;">
        <div style="background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px; text-align: center; width: 130px; height: 70px; color: white; display: flex; justify-content: center; align-items: center;">
            <p style="margin: 0;color: white;"><%:Settings saved successfully%></p>
        </div>
    </div>
